工厂模式一之简单工厂
工廠用來生產商品,然后賣給供應商,再由供應商轉手給門店,再賣給顧客 。這樣的一種生產到供應的過程,看看如何應用到我們的程序中。
1.下面以衣服店為例子。
第一步:創建衣服店類。
clothes.js
//創建一個衣服店模型。 var ClothesShop = function (){} ClothesShop.prototype = {sellClothes: function (color){var clothesType = ['Red', 'Blue', 'Yello', 'Green', 'Gray'];var clothes;for(var i = 0, len = clothesType.length; i < len; i++) {if(color === clothesType[i]){clothes = eval('new '+ color); //new Red(); }}//判斷制造的是不是衣服。 Interface.ensureImplements(clothes, Clothes);//出售return clothes;} } /*門店1 var clothesShop1 = new ClothesShop(); */?創建一個門店模型。按照這個模型來實例化門店對象,可以創建多個門店clothesShop1,clothesShop2, clothesShop3..每個門店都有各種漂亮顏色紅藍黃綠灰的衣服。顧客通過type決定要買什么樣的衣服。假設type為'Red',通過實例化衣服類new Red()來生產紅色的衣服。Interface.ensureImplements在鴨式辨型中提過。這里用來檢測衣服是否實現了衣服接口(檢測商品到底合不合格)。
Interface類
var Interface = function (name, methods) {if(!methods) {throw new Error('Methods is undefined.');}if(!Array.isArray(methods)) {throw new Error('Methods is not an array.');}this.name = name;this.methods = [];//自定義方法作為類的依據for(var i = 0, len = methods.length; i < len; i++) {var method = methods[i];if(typeof method !== 'string') {throw new Error('Method name expected to be a string.');break;}this.methods.push(method);} } View CodeensureImplements方法
Interface.ensureImplements = function () {var canFoundMethods = [];if(arguments.length < 2) {throw new Error('Arguments is expected at least 2.');}//取第二個參數("鴨子"的實例),稱為參照對象for(var i = 1, len = arguments.length; i < len; i++) {var interface = arguments[i];//遍歷參照對象的方法名稱,對比檢測對象。for(var j = 0, methodsLength = interface.methods.length; j < methodsLength; j++) {var method = interface.methods[j];if(!arguments[0][method] || typeof arguments[0][method] !== 'function') {//檢測對象沒有的方法名稱則記錄 canFoundMethods.push(method);}}}//最后輸出沒有的方法if(canFoundMethods.length) {throw new Error ('Method ' + canFoundMethods.join(',') + ' was not found.');} } View Code第二步:定義衣服接口Clothes。
//衣服接口。衣服是什么?自定義為衣服制造出來的,可以穿,可以洗,可以曬干的。 var Clothes = new Interface('Clothes', ['make', 'ware', 'wash', 'dry']);定義一個衣服接口,并且自定義具有這四個特點的就是衣服。接口就是一個規則,用來檢測對象具有某些方法的手段。
//定義紅色衣服的模型。 var Red = function (){}; Red.prototype = {color: function (){return 'Red';},make: function (){},ware: function (){},wash: function (){},dry: function (){} }定義衣服模型。按照這個模型可以生產很多紅色的衣服new Red()。當然這里也可以是其它的衣服模型var Green = function (){},Green.prototype = {..};
第三步:實例化ClothesShop類,調用sellClothes方法。
//按照衣服門面店的模型,創建一個衣服店。當然也可以創建N個店,clothesShop1,clothesShop2... var clothesShop = new ClothesShop(); //指定你要的選的顏色,買新的衣服 var yourNewClothes = clothesShop.sellClothes('Red');當clothesShop調用sellClothes方法時,就像顧客下訂單,然后由店來生產衣服,檢測,最后出售。簡單的工廠模式完成了,可以高興一下。但是還是存在著一點問題,這里存在clothesShop既是門店,也是生產衣服的工廠。明顯不符合我們的邏輯。我們肯定想的是把工廠和門店要分開。
第四步:創建工廠對象
//===============工廠制造衣服==================//把制造工作交給工廠,商店只負責出售衣服,分工明確。 var clothesFactory = {createClothes: function (color) {var clothesType = ['Red', 'Blue', 'Yello', 'Green', 'Gray'];var clothes;for(var i = 0, len = clothesType.length; i < len; i++) {if(color === clothesType[i]){clothes = eval('new '+ color); //new Red(); }}//判斷制造的是不是衣服。 Interface.ensureImplements(clothes, Clothes);//衣服出廠return clothes;} }用一個名為clothesFactory的工廠對象來實現createClothes方法。這樣要需要的時候就可以在sellClothes調用createClothes方法。
第五步:修改ClothesShop類
//創建一個衣服門店模型。 var ClothesShop = function (){} ClothesShop.prototype = {sellClothes: function (color){var clothes = clothesFactory.createClothes(color);//出售return clothes;} }修改ClothesShop門店模型,只負責出售衣服。到這里簡單工廠完成了。
完整代碼:
clothes.js
1 /** 2 * Created by Song_yc on 2015/2/2. 3 */ 4 //創建一個衣服門面店模型。 5 var ClothesShop = function (){} 6 ClothesShop.prototype = { 7 sellClothes: function (color){ 8 var clothes = clothesFactory.createClothes(color); 9 //出售 10 return clothes; 11 } 12 } 13 /*門店1 14 var clothesShop1 = new ClothesShop(); 15 門店2 16 var clothesShop2 = new ClothesShop(); 17 門店3 18 var clothesShop3 = new ClothesShop();*/ 19 20 var Interface = function (name, methods) { 21 if(arguments.length !== 2) { 22 throw new Error('Interface constructor called with' + arguments.length + 'arguments, but expected exactly 2.'); 23 } 24 this.name = name; 25 this.methods = []; 26 if(!Array.isArray(methods)) { 27 throw new Error('The second argument is expected array object instance of ' + typeof method+ '.'); 28 } 29 for(var i = 0, len = methods.length; i < len; i++) { 30 var method = methods[i]; 31 if(typeof method !== 'string') { 32 throw new Error('Interface constructor expects method names to be as a string.'); 33 break; 34 } 35 this.methods.push(method); 36 } 37 } 38 39 Interface.ensureImplements = function () { 40 var canFoundMethods = []; 41 //First to determine argument's length. 42 if(arguments.length < 2) { 43 throw new Error('Arguments is expected at least 2.'); 44 } 45 //Second to determine instance class. 46 for(var i = 1, len = arguments.length; i < len; i++) { 47 var interface = arguments[i]; 48 if(interface.constructor !== Interface) { 49 throw new Error(interface.name + 'object is not instanced of Interface Class.'); 50 } 51 for(var j = 0, methodsLength = interface.methods.length; j < methodsLength; j++) { 52 var method = interface.methods[j]; 53 if(!arguments[0][method] || typeof arguments[0][method] !== 'function') { 54 //throw new Error('Method ' + method + 'was not found.'); 55 canFoundMethods.push(method); 56 } 57 } 58 } 59 //canFoundMethods.forEach(function (methodName) { 60 // throw new Error('Method ' + methodName + 'was not found.'); 61 //}) 62 if(canFoundMethods.length) { 63 throw new Error ('Method ' + canFoundMethods.join(',') + ' was not found.'); 64 } 65 } 66 //定義衣服類。衣服是什么?被制造出來的,可以穿,可以洗,可以曬干的。 67 var Clothes = new Interface('Clothes', ['make', 'ware', 'wash', 'dry']); 68 //定義紅色衣服的模型。 69 var Red = function (){}; 70 Red.prototype = { 71 color: function (){return 'red';}, 72 make: function (){}, 73 ware: function (){}, 74 wash: function (){}, 75 dry: function (){} 76 } 77 78 //===============工廠制造衣服================== 79 80 //把制造工作交給工廠,商店只負責出售衣服,分工明確。 81 var clothesFactory = { 82 createClothes: function (color) { 83 var clothesType = ['Red', 'Blue', 'Yello', 'Green', 'Gray']; 84 var clothes; 85 for(var i = 0, len = clothesType.length; i < len; i++) { 86 if(color === clothesType[i]){ 87 clothes = eval('new '+ color); //new Red(); 88 } 89 } 90 //判斷制造的是不是衣服。 91 Interface.ensureImplements(clothes, Clothes); 92 //衣服出廠 93 return clothes; 94 } 95 } 96 97 //按照衣服門面店的模型,創建一個衣服店。當然也可以創建N個店,clothes1,clothes2... 98 var clothesShop = new ClothesShop(); 99 //選擇喜歡的顏色 100 var yourNewClothes = clothesShop.sellClothes('Red'); View Codeindex.html
<!DOCTYPE html> <html> <head lang="en"><meta charset="UTF-8"><title></title> </head> <body><script src="clothes.js"></script> </body> </html> View Code最后看看新的衣服。
2.總結:
回顧一下:首先創建一個門店模型,擁有生產各色衣服的方法。然后定義衣服接口,創建紅色衣服模型,通過接口檢測衣服是否合格。實例化門店,門店按照顧客的喜好進行生產衣服,檢測,出售。最后把門店生產獨立設計成簡單工廠,生產和門店分離。
- 簡單工廠方法就是把創建類實例的方法放在外部對象,當實例化對象時在外部對象中進行。
轉載于:https://www.cnblogs.com/Songyc/p/4268194.html
總結
以上是生活随笔為你收集整理的工厂模式一之简单工厂的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 考试系统(未完成的小程序)
- 下一篇: JS常用的设计模式(7)—— 外观模式