標籤:
原廠模式是管理對象的一種設計模式,通過向外提供一個公用方法用於建立對象。把使用對象的部分與建立對象的部分分離,建立對象部分與對象建立前的初始化分離,職責分離。jQuery.Callbacks是一個工廠,每次調用都會返回一個對象,並且根據傳入的不同參數值返回的對象具有不同的特徵。
1.簡單原廠模式
在Factory 方法中,根據傳入的參數建立相應的對象,並且返回。
function Orange(){ this.color = ‘orange‘; } function Apple(){ this.color = ‘red‘; } function Banana(){ this.color = ‘yellow‘; } // 建立對象的工廠 function SimpleFactory(type){ var fruit = null; switch(type){ case ‘orange‘: fruit = new Orange(); break; case ‘apple‘: fruit = new Apple(); break; case ‘banana‘: fruit = new Banana(); } return fruit; } //測試 var apple = SimpleFactory(‘apple‘); console.log(apple.color); var banana = SimpleFactory(‘banana‘); console.log(banana.color);
簡單原廠模式只能產生Factory 方法中指定類型的對象,當需要添加其他類型的對象時,需要在Factory 方法中添加相對應的代碼。
2.原廠模式
原廠模式對簡單原廠模式改進,可以擴充新的類型的對象,並且不用修改Factory 方法。
function Fruit(){} Fruit.prototype.say = function(){ return ‘hello,my name is ‘ + this.name; } Fruit.Apple = function (){ this.name = ‘apple‘; } Fruit.Banana = function(){ this.name = ‘banana‘; } Fruit.Orange = function(){ this.name = ‘orange‘; } Fruit.factory = function(type){ var fruit = null; //如果建構函式不存在,返回 if(typeof Fruit[type] !== ‘function‘){ return; } //使用原型繼承父類 if(typeof Fruit[type].prototype.getColor !== ‘function‘){ Fruit[type].prototype = new Fruit(); } //建立對象 fruit = new Fruit[type](); return fruit; } //測試 var apple = Fruit.factory("Apple"); console.log(apple.say());
js 原廠模式