1. 程式人生 > >javascript設計模式--簡單工廠模式

javascript設計模式--簡單工廠模式

簡單工廠模式(simple Factory):又叫靜態工廠方法,由一個工廠物件決定建立某一種產品物件類的例項。主要用來建立同一類物件。

舉個例子,比如說體育商品店賣體育器材,裡面有很多體育用品,及其相關介紹等,當你來到體育用品店賣一個籃球和它的相關介紹的時候,你只需要問售貨員,他會幫你找到你所需要的東西。

//basketball base class
var Baseketball = function(){
  this.intro = 'baseketball is hotting at unitedstates';
}
Baseketball.prototype = {
  getMember : function(){\
    console.log('each team needs five players');
  },
  getBallSize : function(){
    console.log('basketball is big');
  }
}
//football base class 
var Football = function(){
  this.intro = 'football is popular at all of the world';
}
Football = function(){
  getMember = function(){

  },
  getBallSize = function(){

  }
}
//sport factory
var SportsFactory = function(name){
  switch(name){
    case 'NBA':
      return new Baseketball();
    case 'wordCup':
      return new Football();
  }
}

//when you want football 
var football = SportsFactory('wordCup');
console.log(football);
console.log(football.intro);
football.getMember();

簡單工廠模式的理念就是建立物件,對不同類的例項化;只需要建立一個物件,然後通過對這個物件大量的方法和屬性,並在最終將物件返回出來。