javascript程序员

3. 建造者模式

2018-01-06  本文已影响23人  在宇宙Debugger

设计模式并非是难以理解, 或是难以应用到实践中的, 相反的, 设计模式恰恰代表了某些场景下的最佳实践! 这些设计模式通常被有经验的开发者们所采用。
设计模式是开发者们在开发过程中面临的一般问题的解决方案。 这些解决方案是众多开发者们经过长时间的实验和错误所总结出来的
本文将讲解前端 (javascript) 的设计模式概念!


建造者模式的封装性很好, 建造者模式不要求调用者了解构建过程, 只需要关注结果, 在多人协作中这种模式是非常常见的

建造者模式要素

这是在网上找到的一段比较符合建造者模式的定义

产品类(Product): 一般是一个较为复杂的对象, 也就是说创建对象的过程比较复杂, 一般会有比较多的代码量。
抽象建造者类(Builder): 将建造的具体过程交与它的子类来实现,这样更容易扩展。
建造者类ConcreteBuilder: 组建产品;返回组建好的产品。
指导类Director: 负责调用适当的建造者来组建产品,指导类一般不与产品类发生依赖关系,与指导类直接交互的是建造者类

建造者模式的例子

如我们要实现一个仓库检查系统
每个仓库都需要检查

// 产品类, 最终的检查结果
function Result() {
    this.lamp = false;
    this.length = false;
    this.fireproof = false;
}

Result.prototype.getResult = function () {
    return {
        lamp: this.lamp,
        length: this.length,
        fireproof: this.fireproof
    }
}

// 抽象生产者, 检查过程需要一致
function Inspect(data) {
    var placeholder = function () { };
    this.checkLamp = data.checkLamp || placeholder;
    this.checkLength = data.checkLength || placeholder;
    this.checkFireproof = data.checkFireproof || placeholder;
    this.getResult = data.getResult || placeholder;
}

// 指导者
function Director(builder) {
    this.builder = builder;
}

Director.prototype.build = function () {
    var builder = this.builder;
    builder.checkLamp();
    builder.checkLength();
    builder.checkFireproof();
    return builder.getResult();
}

// 仓库1
function Warehouse1() {
    var result = new Result();
    return new Inspect({
        // 检查1号仓库的灯
        checkLamp: function () {
            result.lamp = true;
        },
        // 检查1号仓库的货物数量
        checkLength: function () {
            result.length = true;
        },
        // 检查1号仓库的防火情况
        checkFireproof: function () {
            result.fireproof = true;
        },
        // 返回
        getResult: function () {
            return result;
        }
    });
}

// 仓库2
function Warehouse1() {
    var result = new Result();
    return new Inspect({
        // 检查2号仓库的灯
        checkLamp: function () {
            result.lamp = true;
        },
        // 检查2号仓库的货物数量
        checkLength: function () {
            result.length = true;
        },
        // 检查2号仓库的防火情况
        checkFireproof: function () {
            result.fireproof = true;
        },
        // 返回
        getResult: function () {
            return result;
        }
    });
}

// 检查1号仓库
var warehouse1 = new Warehouse1(); // 创建一号仓库的检查
var director1 = new Director(warehouse1); // 创建指导者
var result1 = director1.build(); // 执行检查并返回结果

// 检查2号仓库
var warehouse2 = new Warehouse1(); // 创建二号仓库的检查
var director2 = new Director(warehouse2); // 创建指导者
var result2 = director2.build(); // 执行检查并返回结果

其他设计模式

单例模式: https://www.jianshu.com/p/4c0604f116ba
构造函数模式: https://www.jianshu.com/p/cf809d980459
简单工厂模式: https://www.jianshu.com/p/4293450926c2
抽象工厂模式: https://www.jianshu.com/p/d6138f36e6e2
装饰者模式: https://www.jianshu.com/p/16cf284ab810
外观模式: https://www.jianshu.com/p/179ae2a13c59

上一篇下一篇

猜你喜欢

热点阅读