日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 >

JavaScript设计模式学习——builder pattern(建造者模式)

發(fā)布時(shí)間:2025/7/25 77 豆豆
生活随笔 收集整理的這篇文章主要介紹了 JavaScript设计模式学习——builder pattern(建造者模式) 小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

個(gè)人理解的應(yīng)用場景

舉個(gè)例子,比如想要?jiǎng)?chuàng)建各種類型的車的實(shí)例,車的類型有很多種,但創(chuàng)建每種類型車的接口定義可能是一樣的,就用到了此模式

相關(guān)概念的通俗解釋

  • 上述例子中接口的定義叫builder
  • 接口到每種類型的車的具體實(shí)現(xiàn)叫concrete builder
  • 真正用于創(chuàng)建車的類叫director
  • 實(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)容,希望文章能夠幫你解決所遇到的問題。

    如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。