Singleton: How should it be used

后端 未结 24 2475
Happy的楠姐
Happy的楠姐 2020-11-22 04:57

Edit: From another question I provided an answer that has links to a lot of questions/answers about singletons: More info about singletons here:

So I have read th

24条回答
  •  感动是毒
    2020-11-22 05:09

    Answer:

    Use a Singleton if:

    • You need to have one and only one object of a type in system

    Do not use a Singleton if:

    • You want to save memory
    • You want to try something new
    • You want to show off how much you know
    • Because everyone else is doing it (See cargo cult programmer in wikipedia)
    • In user interface widgets
    • It is supposed to be a cache
    • In strings
    • In Sessions
    • I can go all day long

    How to create the best singleton:

    • The smaller, the better. I am a minimalist
    • Make sure it is thread safe
    • Make sure it is never null
    • Make sure it is created only once
    • Lazy or system initialization? Up to your requirements
    • Sometimes the OS or the JVM creates singletons for you (e.g. in Java every class definition is a singleton)
    • Provide a destructor or somehow figure out how to dispose resources
    • Use little memory

提交回复
热议问题