Application of singleton pattern

Advantages of the singleton pattern

  • Because the singleton pattern has only one instance in memory, it reduces the memory cost, especially when an object needs to be created and destroyed frequently, and the performance cannot be optimized during creation or destruction, the singleton pattern has obvious advantages.
  • Because the singleton mode generates an instance, it reduces the overhead of system performance. When more resources are needed to generate an object, such as reading configuration or generating other dependent objects, a singleton can be directly produced when the application is started. This is then resolved by permanently resident memory (note the JVM garbage collection mechanism when using the singleton pattern in Java EE).
  • The singleton mode can avoid multiple operations on a resource, such as a write file operation. Because only one instance exists in memory, simultaneous write operations on the same resource file are avoided.
  • The singleton pattern can set up global access points in the system, optimize and share resource access, for example, you can design a singleton class, responsible for all data table mapping processing.

Disadvantages of the singleton pattern

  • The singleton pattern generally has no interface, which makes it difficult to extend, and there is almost no other way to extend it than by modifying the code.

    Why can’t singletons add interfaces? Because interfaces make no sense to the singleton pattern, it requires “self-instantiation” and provides a single instance, interfaces and abstract classes cannot be instantiated. Of course, in special cases, singleton pattern can realize interface, be inherited, etc., need to judge from the environment in system development.

  • The singleton pattern is bad for testing. In parallel development, you can’t test until the singleton pattern is complete, and you can’t mock out a monopoly without an interface.

  • The singleton pattern conflicts with the single responsibility principle. A class should implement only one logic, regardless of whether it is a singleton or not, depending on the context. The singleton pattern combines “singleton” and business logic in a single class.

Usage scenarios for the singleton pattern

In a system, a class is required to have only one object. If there are multiple objects, there will be “adverse reactions”. Singleton mode can be adopted, and the specific scenarios are as follows:

  • An environment that requires a unique sequence number to be generated;
  • A shared access point or shared data is needed throughout the project, such as a counter on the Web, which can be saved from logging every refresh to the database using a singleton pattern to keep the value of the counter and ensure that it is thread-safe;
  • Creating an object consumes too many resources, such as accessing IO and database resources.
  • Environments where you need to define a large number of static constants and static methods (such as utility classes) can use the singleton pattern (or, of course, declare it static).

Considerations for the singleton pattern

First, in the case of high concurrency, note the thread synchronization problem in singleton mode.

Such as:

public class Singleton {
    private static Singleton singleton = null;
    private Singleton(a) {}
    
    public static Singleton getSingleton(a) {
        if(singleton == null) {
            singleton = new Singleton();
        }
        returnsingleton; }}Copy the code

This singleton pattern does not cause problems with low concurrency, but when system stress increases and concurrency increases, multiple instances may appear in memory, disrupting initial expectations.

An extension of the singleton pattern

If a class can only produce a fixed number of instances, the need to generate a fixed number of pattern is called a ceiling mode of many cases, it is an extension of the singleton pattern, adopt more cases of mode with limit, we can decide how many instances in memory when the design, can be expanded system, correcting single cases there may be a problem, provide the system response speed. For example, to read a file, we can initialize it at boot time, start a fixed number of Reader instances in memory, and then quickly respond when we need to read a file

Best practices

The singleton pattern is simple and widely used. In Spring, for example, each Bean is a singleton by default. The advantage of this is that the Spring container can manage the life cycle of these beans, deciding when to create them, when to destroy them, what to do when they are destroyed, and so on. If the non-singleton pattern (Prototype type) is used, the management of the beans after initialization is left to the J2EE container, and the Spring container no longer tracks the life cycle of the managed beans.