JavaScript设计模式

学习JavaScript设计模式——工厂模式(一)

2019-03-07  本文已影响0人  小霸王的铲屎官

工厂模式(一)

神奇的魔术师——简单工厂模式

好处

举个例子

  // 篮球基类
  var Baskethall = function() {
    this.intro = '篮球盛行于美国'
  }
  
  Basketball.prototype = {
     getMember: function() {
       console.log('每个队伍需要5名队员')
     },
     getBallSize: function(){
       console.log('篮球很大')
     }
  }  
  
  // 足球基类
  var Football = function() {
    this.intro = '足球在世界范围内很流行';
  }
  
  Football.prototype = {
    getMember: function() {
       console.log('每个队伍需要11名队员-')
    },
    getBallSzie: function() {
       console.log('足球很大')
    }
  }
  
  // 网球基类
  var Tennis = function() {
      this.intro = '每年有很多网球系列赛'
  }
  
  Tennis.prototype = {
    getMember: function() {
       console.log('每个队伍需要1名队员')
    },
    getBallSzie: function() {
       console.log('网球很小')
    }
  }
  
  // 运动工厂
  var SportFactory = function(name) {
    switch(name) {
       case 'NBA':
          return new Baseketball();
       case 'wordCup':
          return new Football();
       case 'FrenchOpen':
          return new Tennis();   
    }
  }

使用的时候

 var football = new SportFactor('wordCup');
 console.log(football)
 console.log(football.intro)
 football.getMember()

例子2

 var PopFactory = function(name) {
   switch(name) {
     case 'alert':
        return new LoginAlert();
     case 'confirm':
        return new LoginConfirm();
     case 'prompt':
        return new LoginPrompt();     
   }
 }

实例代码

  // 工厂模式
  function createBook(name, time, type) {
    // 创建一个对象,并对对象拓展属性和方法
    var o = new Object()
    o.name = name
    o.time = time 
    o.type = type
    o.getName = function(){
      console.log(this.name)
    }
    // 将对象返回
    return o
  }
  
  var book1 = createBook('js book', 2014, 'js')
  var book2 = createBook('css book', 2013, 'css')
  
  book1.getName()
  book2.getName()
  

提示框例子

  // 提示框实例代码
  function createPop(type, text){
   // 创建一个对象,并对对象拓展属性和方法
   var o = new Object()
   o.content = text
   o.show = function() {
     // Todo 显示方法
   }
   
   if(type === 'alert') {
     // 警示框差异部分
   }
   
   if(type === 'prompt') {
     // 提示框差异部分
   }
   
   if(type === 'confirm') {
     // 确认框差异部分
   }
   
   // 将对象返回
   return o
  }
  
  // 创建警示框
  var userNameAlert = createPop('alert', '用户名只能是26个字母和数字')
 

上面两种简单工厂模式

上一篇 下一篇

猜你喜欢

热点阅读