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();

简单工厂模式的理念就是创建对象,对不同类的实例化;只需要创建一个对象,然后通过对这个对象大量的方法和属性,并在最终将对象返回出来。

你可能感兴趣的:(javascript设计模式--简单工厂模式)