Js设计模式

时间:2020-05-01

单例模式

一个类仅有一个实例,并提供一个访问它的全局方法

先看一个例子

<script>
    function Person(name) {
        this.name = name;
    }

    Person.prototype.eat = function () {
        console.log('eat');
    };

    let p1 = new Person('wyzda');
    p1.eat();

    let p2 = new Person('hello');
    p2.eat();

    console.log(p1 === p2);

</script>

这里面的p1和p2不相等,因为是2个对象实例

<script>

    let SingleTest = (function () {
        let instance = null;

        function Person(name) {
            this.name = name;
        }

        Person.prototype.eat = function () {
            console.log('eat');
        };

        return {
            getInstance: (name) => {
                if (instance === null) {
                    instance = new Person(name);
                }
                return instance;
            }
        };
    })();


    let p1 = SingleTest.getInstance('wyzda');
    p1.eat();

    let p2 = SingleTest.getInstance('test');
    p2.eat();

    console.log(p1 === p2);

</script>

以上用闭包就可以解决单例问题

工厂模式

根据不同的参数创建不同的对象

<script>
    function Person() {
    }

    Person.prototype.eat = function () {
        console.log('饭');
    };

    function Dog() {
    }

    Dog.prototype.eat = function () {
        console.log('狗粮');
    };

    // 提供一个方法来创建不同的对象
    function createFactory(objName) {
        switch (objName) {
            case 'person':
                return new Person();
            case 'dog':
                return new Dog();
            //....
        }
    }

    let p = createFactory('person');
    p.eat();

    let d = createFactory('dog');
    d.eat();

</script>