5. 工厂模式
这个模式的创新之处在于,它不需要构造函数就能创建对象。它提供了用于创建对象的通用接口,我们可以在其中指定要创建的工厂(factory)对象的类型。这样一来,我们只需指定对象,然后工厂会实例化并返回这个对象供我们使用。
当对象组件设置起来很复杂,并且我们希望根据所处的环境轻松地创建不同的对象实例时,使用工厂模式就是很明智的选择。在处理许多共享相同属性的小型对象,以及创建一些需要解耦的对象时也可以使用工厂模式。
- // Dealer A
- DealerA = {};
- DealerA.title = function title() {
- return "Dealer A";
- };
- DealerA.pay = function pay(amount) {
- console.log(
- `set up configuration using username: ${this.username} and password: ${
- this.password
- }`
- );
- return `Payment for service ${amount} is successful using ${this.title()}`;
- };
- //Dealer B
- DealerB = {};
- DealerB.title = function title() {
- return "Dealer B";
- };
- DealerB.pay = function pay(amount) {
- console.log(
- `set up configuration using username: ${this.username}
- and password: ${this.password}`
- );
- return `Payment for service ${amount} is successful using ${this.title()}`;
- };
- //@param {*} DealerOption
- //@param {*} config
- function DealerFactory(DealerOption, config = {}) {
- const dealer = Object.create(dealerOption);
- Object.assign(dealer, config);
- return dealer;
- }
- const dealerFactory = DealerFactory(DealerA, {
- username: "user",
- password: "pass"
- });
- console.log(dealerFactory.title());
- console.log(dealerFactory.pay(12));
- const dealerFactory2 = DealerFactory(DealerB, {
- username: "user2",
- password: "pass2"
- });
- console.log(dealerFactory2.title());
- console.log(dealerFactory2.pay(50));
复制代码
6. 观察者模式
观察者(observer)设计模式在许多对象同时与其他对象集通信的场景中用起来很方便。在观察者模式中不会在状态之间发生不必要的事件 push 和 pull;相比之下,所涉及的模块仅会修改数据的当前状态。
- function Observer() {
- this.observerContainer = [];
- }
- Observer.prototype.subscribe = function (element) {
- this.observerContainer.push(element);
- }
- // 下面是从 container 中移除一个元素
- Observer.prototype.unsubscribe = function (element) {
- const elementIndex = this.observerContainer.indexOf(element);
- if (elementIndex > -1) {
- this.observerContainer.splice(elementIndex, 1);
- }
- }
- /**
- * we notify elements added to the container by calling
- * each subscribed components added to our container
- */
- Observer.prototype.notifyAll = function (element) {
- this.observerContainer.forEach(function (observerElement) {
- observerElement(element);
- });
- }
复制代码
7. 命令模式
最后介绍的是命令(command)模式。命令设计模式将方法调用、操作或请求封装到单个对象中,以便我们可以自行传递方法调用。命令设计模式让我们可以从任何正在执行的命令中发出命令,并将责任委托给与之前不同的对象。这些命令以 run() 和 execute() 格式显示。
- (function(){
- var carManager = {
- // 请求的信息
- requestInfo: function( model, id ){
- return "The information for " + model + " with ID " + id + " is foo bar";
- },
- // 现在购买这个 car
- buyVehicle: function( model, id ){
- return "You have successfully purchased Item " + id + ", a " + model;
- },
- // 现在 arrange viewing
- arrangeViewing: function( model, id ){
- return "You have successfully booked a viewing of " + model + " ( " + id + " ) ";
- }
- };
- })();
复制代码
小结
对于 JavaScript 开发人员来说,使用设计模式的好处很多。设计模式的一些主要优点包括提升项目的可维护性,还能减少开发周期中不必要的工作。JavaScript 设计模式可以为复杂的问题提供解决方案,提升开发速度并提高生产率。但并不能说这些设计模式就可以让开发人员偷懒了。
|
|