javascript设计模式——建造者模式

2018-03-29  本文已影响0人  蟹老板爱写代码

特点:工厂模式的特点是创建的结果都是一个完整的个体,我们对创建过程不得而知,我们只了解得到的创建结果对象。而建造者模式中我们关心的是对象的创建过程,因此我们通常将创建对象的类模块化,这样使被创建的类的每一个模块都可以得到灵活的运用与高质量的复用。

实现:创建一位应聘者,分别有基础信息类(技能和爱好),姓名解析类(分隔FirstName和LastName)和期望职位类(职位名称,职位描述)

Human类

    var Human = function(param) {
      // 技能
      this.skill = param && param.skill || '保密'
      // 兴趣爱好
      this.hobby = param && param.hobby || '保密'
    }
    Human.prototype = {
      getSkill: function() {
        return this.skill
      },
      getHobby: function() {
        return this.hobby
      }
    }

姓名处理类

    var Named = function(name) {
      var that = this;
      (function(name, that) {
        that.wholeName = name
        if(name.indexOf(' ') > -1) {
          that.FirstName = name.slice(0, name.indexOf(' '))
          that.secondName = name.slice(name.indexOf(' '))
        }
      })(name, that)
    }

职位处理类

    var Work = function(work) {
      var that = this;
      (function(work, that){
        switch(work) {
          case 'code':
            that.work = '工程师'
            that.workDescript = '每天撸代码'
            break
          case 'UI':
            that.work = '设计师'
            that.workDescript = '画画画'
            break
          default:
            that.work = work
            that.workDescript = '不知道这个职业'
        }
      })(work, that)
    }
    Work.prototype.changeWork = function(work) {
      this.work = work
    }
    Work.prototype.changeDescript = function(setence) {
      this.workDescript = setence
    }

应聘者创建类

    var Person = function(name, work) {
      var _person = new Human()
      _person.name = new Named(name)
      _person.work = new Work(work)
      return _person
    }

执行结果

    var zhengguorong = new Person('zheng guorong', 'code')
    console.log(zhengguorong.skill) // 保密
    console.log(zhengguorong.name.FirstName) // zheng
    console.log(zhengguorong.work.workDescript) // 每天撸代码
    zhengguorong.work.changeWork('UI')
    console.log(zhengguorong.work.work) // UI
上一篇下一篇

猜你喜欢

热点阅读