学习JavaScript设计模式(四)

Facade(外观)模式

Facade模式的作用是:将复杂的、大型的代码隐藏起来,仅仅提供一个简单清晰的API接口给开发人员。提高代码的可用性。
例如:在JQuer中:

// 以下是$.ajax()的外观:
$.get();
$.post();
$.getJSON();
$.getScript();

Facade模式不是必须单独使用。它们可以与其他模式集成,如Model模式。

/**
 * Created by Zang on 2017/3/20.
 */

var model = (function () {
    var private = {
        i: 5,
        get: function () {
            return this.i;
        },
        set: function (val) {
            this.i = val;
        },
        run: function () {
            console.log('running');
        }
    };
    return {
        facade: function (args) {
            if (args.run) {
                private.run();
                private.set(args.val);
                console.log(private.get());
            }
        }
    };
})();

// 这就是一个外观模式,开发者只需要使用 facade 方法,就可以执行函数内部的一大串程序。
model.facade({run: true, val: 10});

Facade模式使用的场景:

  • 设计初期:有意识的将不同的两个层分离,在它们之间建立 Facade。使用 Facade 进行交互。
  • 开发阶段:随着子系统越来越复杂,增加 Facade,减少它们之间的依赖。
  • 维护阶段:为遗留系统建立一个 Facade 类,提供一个清晰的接口,与新系统进行交互。

Factory(工厂)模式

工厂模式实际上就是提供一个通用的接口来创建对象,简化创建对象的复杂性。
简单实现:

/**
 * Created by Zang on 2017/3/20.
 */

'use strict';

function Car(options) {
    this.color = options.color || 'silver';
    this.doors = options.doors || 4;
    this.state = options.state || 'brand new';
}

function Truck(options) {
    this.color = options.color || 'blue';
    this.wheelSize = options.wheelSize || 'large';
    this.state = options.state || 'used';
}

function VehicleFactory() {
}

VehicleFactory.prototype.vehivleClass = Car;
VehicleFactory.prototype.createVehicle = function (options) {
    if (options.type === 'Car') {
        this.vehivleClass = Car;
    }
    else {
        this.vehivleClass = Truck;
    }
    return new this.vehivleClass(options);
};

var vehicle = new VehicleFactory();

var carVehicle = vehicle.createVehicle({
    type: 'Car',
    doors: 2
});

var truckVehicle = vehicle.createVehicle({
    type: 'Truck',
    wheelSize: 'small'
});

// true
console.log(carVehicle instanceof Car);
// Car : color: "silver", doors: 2, state: "brand new"
console.log(carVehicle);
// true
console.log(truckVehicle instanceof Truck);
// Truck : color: "blue", wheelSize: "small", state: "used"
console.log(truckVehicle);

Factory模式使用场景:

  • 当对象或者组件设置设计高复杂性时
  • 当需要更具不同环境轻松生成对象的不同实例时
  • 当处理很多共享相同属性的小型对象或组件时
  • 在编写只需要满足一个API契约(也称鸭子类型)的其他对象的实例对象时

缺点:

  • 这种模式会给程序打来不必要的复杂性
  • 由于对象创建的过程实际上是藏身接口之后抽象出来的,单元测试也可能带来问题

猜你喜欢

转载自blog.csdn.net/qq_20282263/article/details/64132242
今日推荐