What are the real world applications of the singleton pattern?

后端 未结 10 558
南旧
南旧 2021-02-01 07:22

Duplicate

On design patterns: When should I use the singleton?

class Singleton
{
    private static Singleton instance;

    private Singleton() {}

             


        
10条回答
  •  说谎
    说谎 (楼主)
    2021-02-01 08:04

    A good example of where I've used a Singleton is in an application that had to call a web service component from several places within the application. I needed to maintain state, initialize some fields, and maintain a queue of calls and callbacks, so I couldn't just make static calls. But I wanted only one instance to be reused throughout the application. I implemented this "service" class as a singleton, so that I could call it all over the app in response to many different events, but they were all handled in one single place.

    In my experience, I've used singletons where an object was going to be used many times over the life of the app, required initialization, and/or was memory heavy. Basically where having only one instance of a class where you could potentially have many instances and it would be costly to do so.

提交回复
热议问题