天天看點

設計模式——工廠模式(諸葛韓信總結版)

工廠模式就是建立一個對象,然後該對象可以批量産生需要的資料。一個工廠能提供一個建立對象的公共接口,我們可以在其中指定我們希望被建立的工廠對象的類型。

就像現實中實作了自動化生産的工廠,具有統一的流水線,比如生産一個襪子有襪子的設計和襪子的生成兩大部分:襪子設計───原料顔色打樣───定購原料───襪子打樣───确定工藝;襪體生産-——下機檢驗————縫頭拷口——定型整燙———整理包裝;不一樣的襪子制作,隻需要改變原料、顔色和樣式就可以制作出來不一樣的産品。

工廠模式有三種模式,簡單工廠模式、複雜工廠模式、抽象工廠模式。我們這一章主要探究簡單工廠模式和複雜工廠模式。

一、簡單工廠模式

簡單工廠模式又叫靜态工廠模式,由一個工廠對象決定建立某一種産品對象類的執行個體。主要用來建立同一類對象。因為簡單工廠模式比較簡單,傳遞的參數比較少,而且不需要知道函數内部的方法具體的邏輯。

比如說上邊的例子,一個工廠需要生産一些襪子和褲子以及鞋子,那麼隻需要建構一個簡單的工廠模式,如下:

let UserFactory = function (product) {
  function Clothes() {
    this.name = "衣服"
    this.colors= ['red', 'white', 'black', 'blue']
    this.styles=['diy', 'circular']
    this.consoleSay=function(){
		console.log("我是衣服")
	}
  }
  function Trousers() {
    this.name = '褲子'
     this.colors= ['red', 'white', 'black', 'blue']
     this.styles=['diy', 'circular']
      this.consoleSay=function(){
		console.log("我是褲子")
	}
  }
  function Shoes() {
    this.name = "鞋子"
    this.colors= ['red', 'white', 'black', 'blue']
    this.styles=['diy', 'circular',‘flat’]
     this.consoleSay=function(){
		console.log("我是鞋子")
	}
  }

  switch (product) {
    case 'Clothes':
      return new Clothes();
      break;
    case 'Trousers':
      return new Trousers();
      break;
    case 'Shoes':
      return new Shoes();
      break;
    default:
      throw new Error('參數錯誤, 可選參數:superAdmin、admin、user');
  }
}

//調用
let Clothes= UserFactory('Clothes');
let Trousers= UserFactory('Trousers') 
let Shoes= UserFactory('Shoes')
           

隻需要傳入生産的物品名稱,那麼就可以生産出一批相對應的産品。但是,這種方式很容易造成修改錯誤,因為當我們需要添加一個“包包”的時候,就得改兩處代碼。這個時候,我們可以考慮使用複雜工廠模式。

二、複雜工廠模式

工廠方法模式跟簡單工廠模式差不多,但是把具體的産品放到了工廠函數的prototype中。這樣一來,擴充産品種類就不必修改工廠函數了,也可以随時重寫某種具體的産品。

function factory(type){
    if(this instanceof factory){
        return new this[type]();
    }else{
        return new factory(type);
    }
}
factory.prototype = {
	 'Clothes': function() {
		this.name = "衣服",
	    this.colors= ['red', 'white', 'black', 'blue']
	    this.styles=['diy', 'circular']
	    this.consoleSay=function(){
			console.log("我是衣服")
		}
	}
	 'Trousers': function() {
		this.name = "褲子",
	    this.colors= ['red', 'white', 'black', 'blue']
	    this.styles=['diy', 'circular']
	     this.consoleSay=function(){
			console.log("我是褲子")
		}
	}
	 'Clothes': function() {
		this.name = "鞋子",
	    this.colors= ['red', 'white', 'black', 'blue']
	    this.styles=['diy', 'circular']
	     this.consoleSay=function(){
			console.log("我是鞋子")
		}
	}
}
var Clothes= factory('Clothes')
           

如果我要添加包包,隻需要在factory的prototype中進行添加就可以,如下:

...
 'Bags': function() {
		this.name = "包包",
	    this.colors= ['red', 'white', 'black', 'blue']
	    this.styles=['diy', 'circular']
	     this.consoleSay=function(){
			console.log("我是包包")
		}
...
           

繼續閱讀