On design patterns: When should I use the singleton?

后端 未结 20 3502
失恋的感觉
失恋的感觉 2020-11-22 02:45

The glorified global variable - becomes a gloried global class. Some say breaking object-oriented design.

Give me scenarios, other than the good old logger where it

20条回答
  •  半阙折子戏
    2020-11-22 03:26

    First of all, let's distinguish between Single Object and Singleton. The latter is one of many possible implementations of the former. And the Single Object's problems are different from Singleton's problems. Single Objects are not inherently bad and sometimes are the only way to do things. In short:

    • Single Object - I need just one instance of an object in a program
    • Singleton - create a class with a static field. Add a static method returning this field. Lazily instantiate a field on the first call. Always return the same object.
    public class Singleton {
        private static Singleton instance;
    
        private Singleton() {}
    
        public static Singleton instance() {
            if (instance == null) {
                instance = new Singleton();
            }
            return instance;
        }
    }
    

    As you can see, "Singleton" pattern in its canonical form is not very testing-friendly. This can be easily fixed, though: just make the Singleton implement an interface. Let's call it "Testable Singleton" :)

    public class Singleton implements ISingleton {
        private static Singleton instance;
    
        private Singleton() {}
    
        public static ISingleton instance() {
            if (instance == null) {
                instance = new Singleton();
            }
            return instance;
        }
    }
    

    Now we can mock Singleton because we use it via the interface. One of the claims is gone. Let's see if we can get rid of another claim - shared global state.

    If we strip Singleton pattern down, at its core it's about lazy initialization:

    public static ISingleton instance() {
        if (instance == null) {
            instance = new Singleton();
        }
        return instance;
    }
    

    That's the whole reason for it to exist. And that's the Single Object pattern. We take it away and put to the factory method, for instance:

    public class SingletonFactory {
        private static ISingleton instance;
    
        // Knock-knock. Single Object here
        public static ISingleton simpleSingleton() {
            if (instance == null) {
                instance = new Singleton();
            }
            return instance;
        }
    }
    

    What's the difference with our Testable Singleton? There is none, because this is the essense of the Single Object pattern - it doesn't matter whether you implement it as a Singleton or a Factory Method or a Service Locator. You still have some shared global state. This can become a problem if it's accessed from multiple threads. You will have to make simpleSingleton() synchronized and cope with all the multithreading issues.

    One more time: whatever approach you choose, you will have to pay the Single Object price. Using a Dependency Injection container just shifts the complexity to the framework which will have to cope with Single Object's inherent issues.

    Recap:

    1. Most of people who mention Singleton mean Single Object
    2. One of the popular ways to implement it is the Singleton pattern
    3. It has its flaws that can be mitigated
    4. However, the most of Singleton's complexity roots in Single Object's complexity
    5. Regardless of how you instantiate your Single Object, it's still there, be it a Service Locator, a Factory Method or something else
    6. You can shift the complexity to a DI container which is (hopefully) well-tested
    7. Sometimes using the DI container is cumbersome - imagine injecting a LOGGER to every class

提交回复
热议问题