當(dāng)前位置:
首頁 >
前端技术
> javascript
>内容正文
javascript
JavaScript设计模式学习——builder pattern(建造者模式)
生活随笔
收集整理的這篇文章主要介紹了
JavaScript设计模式学习——builder pattern(建造者模式)
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
個(gè)人理解的應(yīng)用場景
舉個(gè)例子,比如想要?jiǎng)?chuàng)建各種類型的車的實(shí)例,車的類型有很多種,但創(chuàng)建每種類型車的接口定義可能是一樣的,就用到了此模式
相關(guān)概念的通俗解釋
實(shí)現(xiàn)模式的思路
1.首先要定義builder的接口
2.然后各個(gè)concretebuilder類去實(shí)現(xiàn)這個(gè)接口
3.director中接收一個(gè)builder實(shí)例作為參數(shù),最后返回一個(gè)一類車的實(shí)例
示例代碼
function Director() {this.construct = function (builder) {builder.step1();builder.step2();return builder.get();} } //由于js不支持接口,我個(gè)人認(rèn)為其實(shí)應(yīng)當(dāng)typescript定義一個(gè)接口,然后下面兩個(gè)類去實(shí)現(xiàn)這個(gè)接口 function CarBuilder() {this.car = null;this.step1 = function () {this.car = new Car();};this.step2 = function () {this.car.addParts();};this.get = function () {return this.car;}; }function TruckBuilder() {this.truck = null;this.step1 = function () {this.truck = new Truck();};this.step2 = function () {this.truck.addParts();};this.get = function () {return this.truck;}; }function Car() {this.doors = 0;this.addParts = function () {this.doors = 4;};this.say = function () {log.add("I am a " + this.doors + "-door car");}; }function Truck() {this.doors = 0;this.addParts = function () {this.doors = 2;};this.say = function () {log.add("I am a " + this.doors + "-door truck");}; }//其他開發(fā)者使用代碼段 new Director().construct(new CarBuilder());轉(zhuǎn)載于:https://www.cnblogs.com/zhangrenjian/p/8552288.html
總結(jié)
以上是生活随笔為你收集整理的JavaScript设计模式学习——builder pattern(建造者模式)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 梳理百年深度学习发展史-七月在线机器学习
- 下一篇: Spark2.X环境准备、编译部署及运行