Use and considerations of the Java singleton pattern

  • 2020-04-01 03:13:31
  • OfStack

1.

1) singleton pattern: ensure that there is only one instance of a class, instantiate and provide this instance to the system

2) singleton pattern classification: hungry singleton pattern (instantiate an object to its reference when the class is loaded), lazy singleton pattern (only instantiate the object when the method to get an instance is called, such as getInstance) (hungry singleton pattern in Java has better performance than lazy singleton pattern, and lazy singleton pattern is generally used in c++)

3) singleton mode elements:

A) private constructor
B) private static references to their own instances
C) a public static method with its own instance as the return value

  Example 2.

Hungry singleton mode:


package com.wish.modedesign;
public class HungrySingleton {
    private static HungrySingleton instance  = new HungrySingleton();
    private HungrySingleton(){
    }
    public static HungrySingleton getInstance(){
        return instance;
    }
}

Lazy singleton:


package com.wish.modedesign;
public class Singleton {
    private Singleton(){

    }
    private static Singleton instance;
    public static synchronized Singleton getInstance(){   //Pay attention to thread safety when multithreading
        if(instance == null){
            instance = new Singleton();
        }
        return instance;
    }
}

The test class Driver. Java


package com.wish.modedesign;
public class Driver {
    public static void main(String[] args) {
        Singleton s1 = Singleton.getInstance();
        Singleton s2 = Singleton.getInstance();
        System.out.println(s1==s2);   //true
    }
}

3. Advantages and applicable scenarios

1) advantages of singleton mode:

There is only one object in memory, saving memory space.
Avoiding the frequent creation of destruction objects can improve performance.
Avoid multiple USES of Shared resources.
Globally accessible.
2) applicable scenarios:

Objects that need to be instantiated and then destroyed frequently.
An object that takes too much time or resources to create but is frequently used.
Stateful utility class object.
Objects that frequently access databases or files.
4. Matters needing attention when using

1) do not use reflection mode to create a singleton, otherwise a new object will be instantiated

2) pay attention to thread safety when using the lazy singleton

3) both the hungry singleton pattern and the lazy singleton pattern construction methods are private, so they cannot be inherited. Some singleton patterns can be inherited (such as the registered pattern).


Related articles: