js 原廠模式簡要介紹

來源:互聯網
上載者:User

標籤:make   console   最好   turn   color   func   ...   通過   返回   

什麼是原廠模式?就好比一個工廠,能造汽車、飛機...,通過對外介面,由顧客決定,來定製哪一款產品。

在js內表現為,一個工廠函數/對象,包含汽車、飛機等子類,提供對外介面,根據參數返回不同子類的執行個體

簡單一實例如下:

var factory= {    car:function(name, size){        this.name= name;        this.size= size;        this.getName= function(){            return this.name        }    },    plane:function(name, size){        this.name= name;        this.size= size;        this.getName= function(){            return this.name        }    },    makeCar:function(name, size){        return new this.car(name, size)    },    makePlane:function(name, size){        return new this.plane(name, size)    },    make:function(type, name, size){        return new this[type](name, size)    }}var o= factory.make(‘plane‘, ‘波音‘, 1000)console.log(o.getName())

何時使用:

1.對象構建十分複雜

2.需要依賴具體環境建立不同執行個體

3.處理大量具有相同屬性的小對象

優點:

消除對象之間的耦合,將所有執行個體化的代碼放在一個位置以免代碼重複

缺點:

大多數類最好使用new關鍵字和建構函式,可以讓代碼更加簡單易讀。而不必去查看Factory 方法來知道

js 原廠模式簡要介紹

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.