前端常用的设计模式和使用场景

设计原则

最重要的思想:开放封闭原则

对扩展开放

对修改封闭

工厂模式

用一个工厂函数,创建一个实例,封装创建的过程。

class Foo { ... }

function factory(): Foo {
    // 封装创建过程,这其中可能有很多业务逻辑

    return new Foo(...arguments)
}

应用场景

- jQuery `$('div')` 创建一个 jQuery 实例

- React `createElement('div', {}, children)` 创建一个 vnode

单例模式

全局唯一的实例(无法生成第二个)

class SingleTon {
    private static instance: SingleTon | null = null
    private constructor() {}
    public static getInstance(): SingleTon {
        if (this.instance === null) {
            this.instance = new SingleTon()
        }
        return this.instance
    }
    fn1() {}
    fn2() {}
}

// const s1 = new SingleTon() // Error: constructor of 'singleton' is private

const s2 = SingleTon.getInstance()
s2.fn1()
s2.fn2()

const s3 = SingleT

猜你喜欢

转载自blog.csdn.net/m0_38066007/article/details/124941039