ReactNote icon indicating copy to clipboard operation
ReactNote copied to clipboard

《深入设计模式》—— 单例模式

Open BUPTlhuanyu opened this issue 3 years ago • 0 comments

A:什么是单例模式? B:是一种创建型设计模式, 让你能够保证一个类只有一个实例, 并提供一个访问该实例的全局节点。 A:为什么需要单例模式? B:有的场景下我们可能需要在不同的模块中共享一些数据,但是又不想利用全局变量来实现,因为那样的方式会在其他开发者无感知的情况下修改了全局变量的值。

单例模式的实现方式之一

单例的获取只能通过类的公共静态方法getInstance获取,而且通过将类的静态属性instance私有化来阻止修改以创建的单例

/**
 * The Singleton class defines the `getInstance` method that lets clients access
 * the unique singleton instance.
 */
class Singleton {
    private static instance: Singleton;

    /**
     * The Singleton's constructor should always be private to prevent direct
     * construction calls with the `new` operator.
     */
    private constructor() { }

    /**
     * The static method that controls the access to the singleton instance.
     *
     * This implementation let you subclass the Singleton class while keeping
     * just one instance of each subclass around.
     */
    public static getInstance(): Singleton {
        if (!Singleton.instance) {
            Singleton.instance = new Singleton();
        }

        return Singleton.instance;
    }

    /**
     * Finally, any singleton should define some business logic, which can be
     * executed on its instance.
     */
    public someBusinessLogic() {
        // ...
    }
}

使用方式

/**
 * The client code.
 */
function clientCode() {
    const s1 = Singleton.getInstance();
    const s2 = Singleton.getInstance();

    if (s1 === s2) {
        console.log('Singleton works, both variables contain the same instance.');
    } else {
        console.log('Singleton failed, variables contain different instances.');
    }
}

clientCode();

BUPTlhuanyu avatar Oct 14 '21 01:10 BUPTlhuanyu