js设计模式(存储库-策略-访问者)

存储库(Memento)

Memento 表示存储库,其存储对象的状态。在应用程序中可能存在需要保存和恢复对象状态的场景。大多数时候,使用 JSON 的对象的序列化和反序列化属性有助于实现这种设计模式。

var Toy = function (name, country, city, year) {
    this.name = name;
    this.country = country;
    this.city = city;
    this.year = year;
}

Toy.prototype = {
    encryptLabel: function () {
        var memento = JSON.stringify(this);
        return memento;
    },

    decryptLabel: function (memento) {
        var m = JSON.parse(memento);
        this.name = m.name;
        this.country = m.country;
        this.city = m.city;
        this.year = m.year;
        console.log(m);
    }
}

function print() {
    var darth = new Toy("Darth Vader", "USA", "2022");
    darth.encryptLabel();
    darth.decryptLabel();
}

策略模式

策略设计模式用于封装算法,可以用来完成特定的任务。基于某些前提条件,实际执行的策略(别名方法)会发生变化。这意味着策略中使用的算法是高度可互换的。

在我们的玩具工厂,我们使用三个不同的公司运送产品:FedEx、USPS 和 UPS。最终的运输成本取决于公司。因此,我们可以使用策略设计模式来决定最终成本。

Distributor.prototype = {
    setDistributor: function (company) {
        this.company = company;
    },

    computeFinalCost: function () {
        return this.company.compute();
    }
};

var UPS = function () {
    this.compute = function () {
        return "$45.95";
    }
};

var USPS = function () {
    this.compute = function () {
        return "$39.40";
    }
};

var Fedex = function () {
    this.compute = function () {
        return "$43.20";
    }
};

function run() {
    var ups = new UPS();
    var usps = new USPS();
    var fedex = new Fedex();
    var distributor = new Distributor();
    distributor.setDistributor(ups);
    console.log("UPS Strategy: " + distributor.computeFinalCost());
    distributor.setDistributor(usps);
    console.log("USPS Strategy: " + distributor.computeFinalCost());
    distributor.setDistributor(fedex);
    console.log("Fedex Strategy: " + distributor.computeFinalCost());
}

访问者模式(Visitor)

最后,我们有访问者设计模式。当必须为一组对象定义新操作时,它很有用。但是,对象的原始结构应该保持不变。当您必须扩展框架或库时,此模式很有用。与本文讨论的其他模式不同,访问者设计模式在 Javascript 中并未广泛使用。为什么? JavaScript 引擎提供了更高级和更灵活的方式来动态添加或删除对象的属性。

var Employee = function (name, salary, vacation) {
    var self = this;

    this.accept = function (visitor) {
        visitor.visit(self);
    };
    this.getSalary = function () {
        return salary;
    };
    this.setSalary = function (salary) {
        salary = salary;
    };
};

var ExtraSalary = function () {
    this.visit = function (emp) {
        emp.setSalary(emp.getSalary() * 2);
    };
};

function run() {
    var john = new Employee("John", 10000, 10),
    var visitorSalary = new ExtraSalary();
      john.accept(visitorSalary);
    }
}

 

版权声明:著作权归作者所有。

thumb_up 0 | star_outline 0 | textsms 0