Yeah.. I know.. I'm a simpleton.. So what's a Singleton?

前端 未结 8 832
囚心锁ツ
囚心锁ツ 2020-12-05 00:47

I\'ve tried a few times to understand what a Singleton is. Perhaps I\'m just too visual.. so can anyone break it down in a simple analogy.

Similar Posts:

8条回答
  •  情书的邮戳
    2020-12-05 01:04

    Singleton is useful when you must be sure that there is one and only one instance of a class, and that this object must be accessed from multiple locations in the code.

    If it could make sense that more than one instance of your class could be used at once, then you don't want a singleton.

    Here is some information about where to use singletons: http://www.ibm.com/developerworks/webservices/library/co-single.html

    From the article mentioned previously:

    To decide whether a class is truly a singleton, you must ask yourself some questions.

    • Will every application use this class exactly the same way? (exactly is the key word)
    • Will every application ever need only one instance of this class?
      (ever and one are the key words)
    • Should the clients of this class be unaware of the application they are
      part of?

      If you answer yes to all three questions, then you've found a singleton. The key points here are that a class is only a singleton if all applications treat it exactly the same and if its clients can use the class without an application context.

提交回复
热议问题