zoukankan      html  css  js  c++  java
  • javaScript设计模式(3)——构造者模式

    模拟场景:客户需要一套房子,他找到包工头(指挥者),包工头分配人员进行相应的具体建造操作,然后工人可以垒墙、造门等基本建造技能,最后建好房子

    /*房子模型*/
    function House() {
        if (!this instanceof House){
            return new House();
        }
        this.bedRoom = 'bed room';
        this.livingRoom = 'living room';
        this.restRoom = 'rest room'
    }
    
    
    /*具体建造类,做具体的事情*/
    function Worker() {
        if (!this instanceof Worker){
            return new Worker();
        }
        this.zaomen = function () {
            console.log('造门');
        }
        this.leiqiang = function () {
            console.log('垒墙');
        }
        this.ankuanghu = function () {
            console.log('安窗户');
        }
        this.get_house = function () {
            var house = new House();
            return house;
        }
    }
    
    
    /*总指挥者,分配人员做具体的事情*/
    function Director() {
        if (!this instanceof Director){
            return new Director();
        }
        this.direct_build = function (worker) {
            worker.zaomen();
            worker.ankuanghu();
            worker.leiqiang();
        }
    }
    
    
    /*客户提需求,总的执行过程,房主请director建房子,director负责人员管理调度,不做具体的事情,房主从工人手中取得房子。*/
    var worker = new Worker();
    var director = new Director(worker);
    director.direct_build(worker);
    var succ_house = worker.get_house();
    console.log(succ_house);
    

    应用场景:复杂对象(包含若干子对象),随着需求不断的变化,此复杂对象的一部分会剧烈变化,但是整体的组合相对稳定。而我们如何用一种封装方式隔离各种部分的变化而保持整体结构的稳定就是建造者模式的任务。

    一句话汇总:就是复杂对象的构造与表示分离,用户只需要指定类型,不需知道具体过程。

  • 相关阅读:
    妈妈之歌 The Mom Song 中文字幕
    40个实用的轻量级JavaScript库
    2009超强流行词汇
    60+CSS技巧教程资源大全
    关于zindex的那些事儿
    FF和IE之间7个JavaScript的差异
    IE6 不支持PNG问题
    邮件营销EDM模板制作规范
    css层的定位position、absolute、relative层叠加的五条叠加法则
    IE8的CSS hack
  • 原文地址:https://www.cnblogs.com/flora-dn/p/7677255.html
Copyright © 2011-2022 走看看