javascript 单身创造设计模式

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了javascript 单身创造设计模式相关的知识,希望对你有一定的参考价值。

## Real world example
There can only be one president of a country at a time. The same president has to be brought to action, whenever duty calls. President here is singleton.

## In plain words
Ensures that only one object of a particular class is ever created.

## Wikipedia says
In software engineering, the singleton pattern is a software design pattern that restricts the instantiation of a class to one object. This is useful when exactly one object is needed to coordinate actions across the system.

Singleton pattern is actually considered an anti-pattern and overuse of it should be avoided. It is not necessarily bad and could have some valid use-cases but should be used with caution because it introduces a global state in your application and change to it in one place could affect in the other areas and it could become pretty difficult to debug. The other bad thing about them is it makes your code tightly coupled plus it mocking the singleton could be difficult.
const president = (function(){
    const presidentsPrivateInformation = 'Super private'

    const name = 'Turd Sandwich'

    const getName = () => name

    return {
        getName
    }
}())


// IMPLEMENTATION
president.getName() // Outputs 'Turd Sandwich'
president.name // Outputs undefined
president.presidentsPrivateInformation // Outputs undefined

以上是关于javascript 单身创造设计模式的主要内容,如果未能解决你的问题,请参考以下文章

javascript 工厂方法创造性设计模式

Luck Club-SDT超级单身狗 区块链游戏

phpwamp单身狗模式的详解与分析,单身狗模式/即霸体模式的作用讲解。

phpwamp单身狗模式的详解与分析,单身狗模式/即霸体模式的作用讲解。

存储库模式是什么类型的?

java 单身设计模式示例