建造者模式的定义
用途: 创建极其复杂的对象(若不是极其复杂的对象,应选择使用对象字面或工厂模式等方式创建对象)
核心思想:分步构建一个复杂的对象,可以用不同组合或顺序建造出不同意义的对象。
实现原理:通常使用链式调用来进行建造过程,最后调用build
方法生成最终对象。
与工厂模式的区别:
- 工厂模式关注的是创建的结果
- 建造者模式不仅得到了结果,同时也参与了创建的具体过程
演示范例 —— 建造者模式
代码解析:此处将自动创建withxxx
和build
的代码提取为父类BaseBuilder,在创建其他建造者类时继承该父类,这使得在创建多个建造者类时变得十分容易。
//父类 class BaseBuilder { init() { Object.keys(this).forEach(key => { const withName = `with${key.substring(0, 1).toUpperCase()}${key.substring(1)}`; this[withName] = value => { this[key] = value; return this; } }) } build() { const keysNoWithers = Object.keys(this).filter(key => typeof this[key] !== 'function'); return keysNoWithers.reduce((returnValue, key) => { return { ...returnValue, [key]: this[key] } }, {}) } } //子类1: 书籍建造者类 class BookBuilder extends BaseBuilder { constructor() { super(); this.name = ''; this.author = ''; this.price = 0; this.category = ''; super.init(); } } //子类2: 印刷厂建造者类 class printHouseBuilder extends BaseBuilder { constructor() { super(); this.name = ''; this.location = ''; this.quality = ''; super.init(); } } //调用书籍建造者类 const book = new BookBuilder() .withName("高效能人士的七个习惯") .withAuthor('史蒂芬·柯维') .withPrice(51) .withCategory('励志') .build(); //调用印刷厂建造类 const printHouse = new printHouseBuilder() .withName('新华印刷厂') .withLocation('北京海淀区') .withQuality('A') .build();
BaseBuilder类自动创建withxxx
和build
的代码的最终效果如下:
//书籍建造者类 class BookBuilder { constructor() { this.name = ''; this.author = ''; this.price = 0; this.category = ''; } withName(name) { this.name = name; return this; } withAuthor(author) { this.author = author; return this; } withPrice(price) { this.price = price; return this; } withCategory(category) { this.category = category; return this; } build() { return { name: this.name, author: this.author, prices: this.price, category: this.category } } } //调用建造者类 const book = new BookBuilder() .withName("高效能人士的七个习惯") .withAuthor('史蒂芬·柯维') .withPrice(51) .withCategory('励志') .build();
更多设计模式详见——js设计模式【详解】总目录
https://blog.csdn.net/weixin_41192489/article/details/116154815