js原生设计模式——6复杂对象的构建—Builder建造者模式

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>builder</title>
    <script type="text/javascript">
    //创建一个人类
    var Human = function(param){
        //skill技能
        this.skill = param && param.skill || '保密';
        //兴趣爱好
        this.hobby = param && param.hobby || '保密';
    }
    //添加人类的原型方法
    Human.prototype = {
        getSkill:function(){
            return this.skill;
        },
        getHobby:function(){
            return this.hobby;
        }
    }
    //创建姓名类
    var Named = function(name){
        var that = this;
        //构造器函数:解析姓与名(new构造实例时即刻执行此闭包函数)
        (function(name,that){
            that.wholeName = name;//全名赋值
            if (name.indexOf(' ')>-1) {
                that.firstName = name.slice(0,name.indexOf(' '));
                that.secondName = 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 'UI':
                case 'UE':
                    that.work = '设计师';
                    that.workDescript = '设计是一种艺术';
                break;
                case 'teacher':
                    that.work = '教师';
                    that.workDescript = '分享也是一种快乐';
                break;
                default:
                    that.work = work;
                    that.workDescript = 'sorry,we don\'t know your\'s workDescript';
            }
        })(work,that);
    }
    //添加更换职位的方法
    Work.prototype.changeWork = function(work){
        this.work = work;
    }
    //添加对职位的描述方法
    Work.prototype.changeDescript = function(setence){
        this.workDescript = setence;
    }
    //创建一个应聘者builder
    var Person = function(name,work){
        //实例化人对象
        var _person = new Human();
        //实例化人的姓名
        _person.name = new Named(name);
        //实例化人的期望职位
        _person.work = new Work(work);
        //最后将构建的复杂对象应聘者返回出去
        return _person;
    }
    //测试用例
    var person = new Person('小 明','code');

    console.log(person.skill);
    console.log(person.name.firstName);
    console.log(person.work.work);
    console.log(person.work.workDescript);
    person.work.changeDescript('我每天都在快乐的编程学习')
    console.log(person.work.workDescript);


    //本例已经通过验证
    </script>
</head>
<body>
    
</body>
</html>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值