设计模式-工厂模式

例一

        class Product{//构造函数
            constructor(name){
                this.name = name
            }
            init(){
                console.log('init')
            }
            fun1(){
                console.log('fun1')
            }
            fun2(){
                console.log('fun2')
            }
        }

        class Creator{//工厂函数
            create(name){
                return new Product(name)
            }
        }

        //测试
        let creator = new Creator()
        let p = creator.create('p')
        p.init()
        p.fun1()
        p.fun2()

例二

//工厂模式
class Monther {
    // 向妈妈申请所有你想要的  静态方法不需要new 可以直接类名点相应静态方法名 new获取不了静态方法
    static giveMe(whatYouWant) {
        switch (whatYouWant) {
            // 糖糖
            case "tangtang":
                console.log("宝宝,你一个人吃果冻是非常危险的哦,妈妈喂你~~");
                return this.chewJelly(new Jelly);
            // 飞飞
            case "feifei":
                console.log("宝宝,家里已经买了很多飞机了哦,")
                return null;
            default: return null;
        }
    }

    static chewJelly(jelly) {
        jelly.chewed = true;
        return jelly;
    }
}

class Jelly {
    constructor() {
        // 是否咀嚼过的果冻
        this.chewed = false;
    }
}

class ToyPlane {}

let jelly = Monther.giveMe('tangtang'); //宝宝,你一个人吃果冻是非常危险的哦,妈妈喂你~~
let toyPlane = Monther.giveMe('feifei'); //宝宝,家里已经买了很多飞机了哦,

工厂模式

1.能对代码运作有效解耦  创建是创建 运行是运行
2.减少重复代码
3.对于使用者更加友好
使用范围:如果产品类很复杂,而且存在太多变数,其构造过程也很复杂
原文地址:https://www.cnblogs.com/yzyh/p/10305904.html