建造者模式-封装

73 阅读1分钟

建造者模式

建造者模式注重创建对象的细节,使用这种模式创建出的复杂对象或者复合对象结构非常清晰

 var data = [
            {
                name: 'zhang san',
                age: 23,
                work: 'engineer'
            },
            {
                name: 'li si',
                age: 30,
                work: 'teacher'
            },
            {
                name: 'wang wu',
                age: 22,
                work: 'xxx'
            }
        ]
        function Candidate(param) {
            let _candidate = new Person(param)
            _candidate.name = new CreateName(param.name)
            _candidate.work = new CreateWork(param.work)

            return _candidate

        }
        function Person(param) {
            this.name = param.name
            this.age = param.age
        }
        function CreateName(name) {
            this.wholeName = name
            this.firstName = name.split(' ')[0]
            this.lastName = name.split(' ')[1]
        }
        function CreateWork(work) {
            switch (work) {
                case 'engineer':
                    this.name = '工程师'
                    this.description = '热爱编程'
                    break
                case 'teacher':
                    this.name = '老师'
                    this.description = '乐于分享'
                    break
                default:
                    this.name = work;
                    this.description = '无'

            }
            console.log(this.description)

        }
        CreateWork.prototype.changeWork = function (work) {
            this.name = work
        }
        CreateWork.prototype.changeDes = function (des) {
            this.description = des
        }
        var candidateArr = []
        for (var i = 0; i < data.length; i++) {
            candidateArr[i] = Candidate(data[i])
        }
        console.log(candidateArr)