这篇文章主要讲解了如何使用javascript中的建造者模式,内容清晰明了,对此有兴趣的小伙伴可以学习一下,相信大家阅读完之后会有帮助。

介绍:建造者模式又称为生成器模式,它是一种较为复杂、使用频率相对较低的创建型模式。建造者模式为客户端返回的不是一个简单的产品,而是一个由多个部件组成的复杂产品
定义:将一个复杂对象的构建与他的表示分离,使得同样的构建过程可以创建不同的表示。建造者模式是一种对象创建型模式。
示例:
var Dialog = function (){
  this.type = '';
  this.name = '';
  this.element = '';
  this.show = function(){
    console.log(this.name + ': ' + this.type + this.element);
  }
}
 
var noticeBuilder = function(){
  this.dialog = new Dialog();
  this.setType = function(){
    this.dialog.type = 'notice';
  }
  this.setName = function(){
    this.dialog.name = '公告';
  }
  this.setElement = function(){
    this.dialog.element = 'notice';
  }
  this.getDialog = function(){
    return this.dialog;
  }
}
 
var toastBuilder = function(){
  this.dialog = new Dialog();
  this.setType = function(){
    this.dialog.type = 'toast';
  }
  this.setName = function(){
    this.dialog.name = '提示';
  }
  this.setElement = function(){
    this.dialog.element = 'toast';
  }
  this.getDialog = function(){
    return this.dialog;
  }
}
 
function construct(ab){
  ab.setType();
  ab.setName();
  ab.setElement();
  return ab.getDialog();
}
 
var notice = new noticeBuilder();
var toast = new toastBuilder();
var noticeIns = construct(notice);
var toastIns = construct(toast);
 
noticeIns.show(); //公告: noticenotice
toastIns.show(); //提示: toasttoast另外有需要云服务器可以了解下创新互联scvps.cn,海内外云服务器15元起步,三天无理由+7*72小时售后在线,公司持有idc许可证,提供“云服务器、裸金属服务器、高防服务器、香港服务器、美国服务器、虚拟主机、免备案服务器”等云主机租用服务以及企业上云的综合解决方案,具有“安全稳定、简单易用、服务可用性高、性价比高”等特点与优势,专为企业上云打造定制,能够满足用户丰富、多元化的应用场景需求。