设计模式学习-(5. 建造者模式)

建造者模式: 实现的主要是 创建一个复合的对象,最后的对象会由好几个基类合并而成。 不同于之前的模式,之前的工厂模式都是追求创建的结果,

而这里  用于合成的几个类 则是使用时的重点,以此拼合一个更复合需求的对象。


// 创建一位人类
    var Human = function ( param ) {
        // 技能
        this.skill = param && param.skill || '保密';
        // 兴趣爱好
        this.hobby = param && param.hobby || '保密';
    };
    // 人类 原型方法
    Human.prototype = {
        getSkill: function () {
            return this.skill;
        },
        setSkill: function ( skill) {
            this.skill = skill;
        }
    };


    //  建造者模式的创建细节,由多个类复合而成
    // 实例化姓名类
    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.LastName = 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 'teach':
                    that.work = '教师';
                    that.workDescript = '分享也是一种快乐';
                    break;
            }
        })( work , that)
    };
    Work.prototype.changeWork = function (work) {
        this.work = work;
    };
    Work.prototype.changeDes = function ( sentece) {
        this.workDescript = sentece;
    };

    /*创建一个符合成员
    参数 name: 姓名
    参数 work: 期望职位
    由上2个类拼成一个复合需求的类,简单来说就是将一个复杂的类解剖成小类,也就相当于代码的解耦吧*/
    var Person = function ( name , work ) {
        var _person = new Human();
        _person.name = new Named( name );
        _person.work = new Work( work );
        return _person;
    };

    // 实例化
    var p = new Person( 'he he' , 'code' );
    console.log( p.skill );
    p.setSkill( '弹琴');
    console.log( p.getSkill() );
    console.log( p.work.work );
    console.log( p.work.workDescript );
    p.work.changeWork( 'no coding!no Life' );
    console.log( p.work.work );


猜你喜欢

转载自blog.csdn.net/zxf13598202302/article/details/79458829