Javascript设计模式之建造者(四)

创建型设计模式-建造者模式

定义

所谓建造者模式,就是在于细节的考虑,我们需要考虑整体与细节,才能构建出符合条件的设计。也就是我们的类了。
表现层和我们的基层构建需要分离开来。

案例分析

1,求职者需要发布简历在我们平台
2,展示求职者的特长爱好
3,隐藏求职者的个人隐私信息,联系方式等

let Person = function(param){
   this.skill = param && param.skill || '保密'this.hobby = param && param.hobby || '保密';
}
Person.prototype = {
   getSkill(){
    return this.skill 
   }
   getHobby(){
    return this.hobby;
   }
}
let Named = function(name){
  let that = this;
  //构造器
  //构造函数解析姓名的姓与名 function(that,name){
     that.fullName = name;
     if(name.indexOf(' ') !== -1){
       that.firstName = name.slice(0,name.indexOf(' '));
       that.lastName = name.slice(name.indexOf(' '))
     }
   })(that,name);
}
let Work = function(work){
   var that = this;
   (function(that,work){
     switch(work){
       case 'CODER':
         that.work = '软件工程师';
         that.workDescription = '编织码农的世界'
         break;
       case 'UI':
         that.work = '平面设计师';
         that.workDescription = '设计总是那么随意但却不失为美感';
         break;
       case 'UE':
          that.work = '设计师';
          that.workDescription  ='走不一般的路,共通美的永恒'
          break;
       default:
         that.work = work;
         that.workDescription = '抱歉,我们还不清楚你所选择的职位的相关描述'
         break;
     }
   })(that,work)
}
Work.prototype  = {
  changeWork(work){
    this.work = work;
  }
  changeDescription(description){
    this.workDescription = description;
  }
}

创建一个求职者

let JobSeeker =function(name,work){
 // 求职者缓存对象
  let _jobSeeker = new Person();
   // 创建求职者姓名
   _jobSeeker.name = new Named(name);
   //创建求职者期待职位
   _jobSeeker.work = new Work(work);
  return _jobSeeker;
}
//测试
let Anna = new JobSeeker('Anna Chen','UE');
console.log(Anna.name.firstName) // Anna;
console.log(Anna.work.workDescription) // 走不一般的路,共通美的永恒

所有的工厂模式,最终会得到一个整体。
参考书籍: 《JavaScript 设计模式》张容铭
同时大家也可参考这位读者的观后感

猜你喜欢

转载自blog.csdn.net/weixin_39370315/article/details/79790624
今日推荐