zoukankan      html  css  js  c++  java
  • Builder 模式 javascript

    原文:http://www.dofactory.com/javascript-builder-pattern.aspx

    function Shop() {
        this.construct = function(builder) {
            builder.step1();
            builder.step2();
            return builder.get();
        }
    }
    
    function CarBuilder() {
        this.car = null;
        this.step1 = function() {
            this.car = new Car();
        };
        this.step2 = function() {
            this.car.addParts();
        };
        this.get = function() {
            return this.car;
        };
    }
    
    function TruckBuilder() {
        this.truck = null;
        this.step1 = function() {
            this.truck = new Truck();
        };
        this.step2 = function() {
            this.truck.addParts();
        };
        this.get = function() {
            return this.truck;
        };
    }
    
    function Car() {
        this.doors = 0;
        this.addParts = function() {
            this.doors = 4;
        };
        this.say = function() {
            log.add("I am a " + this.doors + "-door car");
        };
    }
    
    function Truck() {
        this.doors = 0;
        this.addParts = function() {
            this.doors = 2;
        };
        this.say = function() {
            log.add("I am a " + this.doors + "-door truck");
        };
    }
    
    // log helper
    var log = (function () {
        var log = "";
        return {
            add: function (msg) { log += msg + "\n"; },
            show: function () { alert(log); log = ""; }
        }
    })();
    
    function run() {
        var shop = new Shop();
    
        var carBuilder = new CarBuilder();
        var truckBuilder = new TruckBuilder();
    
        var car = shop.construct(carBuilder);
        var truck = shop.construct(truckBuilder);
    
        car.say();
        truck.say();
    
        log.show();
    }
  • 相关阅读:
    SVD与PCA
    Service(二):通信
    Service(一):认识service、绑定Service
    计划(四)
    Android studio 安装过程中遇到的问题
    UFLDL 教程学习笔记(四)
    opencv之dft及mat类型转换
    《第一行代码》(四)
    《第一行代码》
    计划(三)
  • 原文地址:https://www.cnblogs.com/wangkangluo1/p/3068822.html
Copyright © 2011-2022 走看看