设计模式之简单工厂模式

234 阅读1分钟

代码:

class Plant {
    constructor(name){
        this.name = name;
    }
    grow(){
        console.log(`我是${name},我在生长`)
    }
}
class Apple extends Plant{
    constructor(name, flaver){
        super(name)
        this.flaver = flaver;
    }
}
class Orange extends Plant {
    constructor(name, flaver) {
        super(name)
        this.flaver = flaver;
    }
}
// 直接new缺点 耦合 依赖具体实现 项目中使用后不能修改
let p1 = new Apple();
let p2 = new Orange();

class Factory {
    static creact(type){
        switch (type) {
            case 'apple':
            return new Apple('苹果', '甜');
            case 'orange':
                return new Orange('橘子','酸');
            default: 
            throw new Error('没有') 
        }
    }
}

let p3 = Factory.creact('apple');
console.log(p3)

简单工厂模式 实例jquery

class Jquery {
    constructor(select){
        this.select = select;
        let elements = document.querySelectorAll(select);
        this.length = elements.length;
        for (let i = 0; i < this.length; i++){
            this[i] = elements[i]
        }
    }
}

window.$=(select)=>{
    return new Jquery(select);
}

// 简单工厂模式  实例react

let h1 = <h1 className='title'>hello</h1>;
let h1 = React.createElement('h1', { className: 'title'}, 'hello');

// 实现
class VNode{
    constructor(tag, attrs, children) {
        this.tag = tag;
        this.attrs = attrs;
        this.children = children;
    }
}

function createElement(tag, attrs, children){
    return new VNode(tag, attrs, children)
}