Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
BUPTlhuanyu opened this issue Oct 14, 2021 · 0 comments
Open

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

BUPTlhuanyu opened this issue Oct 14, 2021 · 0 comments

Comments

@BUPTlhuanyu
Copy link
Owner

BUPTlhuanyu commented Oct 14, 2021

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();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant