发如飞絮——js设计模式(2)

101 阅读1分钟

3.工厂模式(批量制造模板数据)

构造函数式(推荐)

function Createfactory(name, age) {
    this.name = name
    this.age = age

    this.sayInfo = function() {
        console.log(`名字为${name},年龄为${age}`)
    }
}

function callFactory(inputName = '', inputAge = '') {
    new Createfactory(inputName, inputAge).sayInfo();
}

callFactory('lili', 41)

结果为:名字为lili,年龄为41

工厂模型

function Createfactory(name, age) {
    let obj = new Object()
    obj.name = name
    obj.age = age
    obj.sayInfo = function() {
        console.log(`名字为${name},年龄为${age}`)
    }
    return obj
}

function callFactory(inputName = '', inputAge = '') {
    new Createfactory(inputName, inputAge).sayInfo();
}

callFactory('lili', 41)

结果为:名字为lili,年龄为41

4 单体模式

闭包单体(作用域内变量私有,只可通过return暴露)

let single = {}
single.data = (function() {
    let inB = '123'
    return {
        mm: function(inputB) {
            inB = inputB
            return inB
        },
        b: inB
    }
})()

console.log(single.data.mm('a'));
console.log(single.data.b);

结果为:a 123

惰性单体(闭包单体基础上,增加了空对象初始化,节约性能)

let single = {}
single.data = (function() {
    let userInstance // undefined

    function init(inA, inB) {
        let a = inA
        let b = inB
        let f1 = function() {
            console.log(a);
        }
        let f2 = function() {
            console.log(b);
        }
        return {
            aa: a,
            bb: b,
            ff1: function() {
                return f1()
            },
            ff2: function() {
                return f2()
            }
        }
    }
    return {
        getInstance: function(inA, inB) {
            if (!userInstance) {
                userInstance = init(inA, inB)
                    // console.log(userInstance);
            }
            return userInstance
        }
    }
})()

single.data.getInstance('a', 'b').ff1()

结果为 a

题外

实现链式调用

function sheet() {
    console.log('this', this);
    this.wakeUp = function() {
        console.log('我起床了');
        return this
    }

    this.shower = function() {
        console.log('我洗漱了');
        return this
    }

    this.goOut = function() {
        console.log('我出门了');
        return this
    }
}

let p1 = new sheet()
p1.wakeUp().shower().goOut()