js设计模式之工厂模式

所谓工厂模式,就是定义一个用于创建对象的接口,让子类决定实例化哪个类,工厂方法使每一个类的实例化延迟到其子类,下面我们就来写·下简单工厂模式和工厂方法模式

 let shop = (function () {
        class apple {
            constructor() {
                this.name = "apple"
            }
        }
        class pear {
            constructor() {
                this.name = "pear"
            }
        }
        return function (name) {
            var o = null;
            switch (name) {
                case "apple":
                    o = new apple();
                    break;
                case "pear":
                    o = new pear();
                    break;
            }
            return o;
        }
    }());


var obj1=new shop("apple");
var obj2=new shop("pear");

接着是工厂方法模式

class shop {
            constructor(name) {
                if (typeof this[name] === "function") {
                    this[name]();
                } else { throw new Error("类型错误"); }
            }
            apple() {
                this.name = "apple"
            }
            pear() {
                this.name = "pear"
            }
        }

        var obj1 = new shop("apple");
        var obj2 = new shop('pear');

至于抽象工厂,下次再写吧

你可能感兴趣的:(前端)