Singleton Pattern – the creation mode of design pattern:
Catalogue
Single instance implementation method:
Static internal class: Recommended
Enumeration: Recommended Methods
Singleton Pattern
Definition: Ensure a class has only one instance, and provide a global point of access to it
Ensure that there is only one instance of a class and provide a global access point.
Class diagram
General class diagram of singleton mode:
Single instance implementation method:
There are five ways to implement singleton: lazy man, evil man, double check lock, static internal class and enumeration.
hungry man:
public class HungrySingle { private static HungrySingle instance = new HungrySingle(); private HungrySingle(){} public static HungrySingle getInstance(){ return instance; } }
private static HungrySingleton instance = new HungrySingleton();
The method of implementation is thread safe because the instance is created when the class is loaded (except when multiple classloaders exist). Its disadvantage is that it cannot delay loading.
Lazy man:
/** * Deferred loading is the instance created when the get() method is called * */ public class LazySingle { // Delayed loading mode private static LazySingle lazySingle; private LazySingle() { } public static LazySingle getInstance() { // Delayed loading try { if (lazySingle != null) { } else { Thread.sleep(3000); lazySingle = new LazySingle(); } } catch (InterruptedException e) { e.printStackTrace(); } return lazySingle; } }
Lazy implementation method: every time you get an instance, you have to judge, and the efficiency will be reduced. Its advantage is delayed loading.
Double check lock:
public class DCLSingle { private static DCLSingle dclSingle; private DCLSingle() { } public static DCLSingle getInstance() { // Delayed loading try { if (dclSingle != null) { } else { Thread.sleep(3000); synchronized (DCLSingle.class) { if (dclSingle == null) { dclSingle = new DCLSingle(); } } } } catch (InterruptedException e) { e.printStackTrace(); } return dclSingle; } }
The implementation of double check lock can not only realize thread safety, but also make the performance not greatly affected. When you create an instance for the first time, you need not synchronize later, which speeds up the running speed.
Static internal class: Recommended
public class StaticInnerSingle { private static class InnerClassSingleHandler { private static StaticInnerSingle staticInnerSingle = new StaticInnerSingle(); }; private StaticInnerSingle() { } public static StaticInnerSingle getInstance() { return InnerClassSingleHandler.staticInnerSingle; } }
Static internal class implementation can delay loading and reduce memory overhead. Because the static field is loaded only when it is used, it avoids the disadvantage that the static field enters the permanent generation of heap memory when the singleton class is loaded and can never be recycled (this is the case with most garbage collection algorithms).
Enumeration: Recommended Methods
public enum EnumSingle { INSTANCE; // Define an enumerated element, which represents an instance of Singleton. private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } public static void main(String[] args) { EnumSingle instance01 = EnumSingle.INSTANCE; instance01.setName("yan Master"); System.out.println(instance01.getName()); } }
Enumeration implementation can not only avoid the problem of multi-threaded synchronization, but also prevent deserialization and re creation of new objects. However, some features of the class are lost, and there is no delayed loading.
analysis
Among the five singleton implementations, the latter two are more recommended, especially the last enumeration, which is a better singleton implementation. It can be used in many projects.
Summary:
advantage:
1. There is only one instance in memory, which reduces the overhead of memory, especially the frequent creation and destruction of instances (such as the homepage page cache of the school of management).
2. Avoid multiple occupation of resources (such as writing files).
Disadvantages: there is no interface and cannot be inherited, which conflicts with the principle of single responsibility. A class should only care about the internal logic rather than how to instantiate it outside.
Usage scenario
In a system, a class is required to have only one object. If there are multiple objects, there will be "adverse reactions". The singleton mode can be adopted. The specific scenarios are as follows:
1. The environment where the unique serial number is required to be generated;
2. A shared access point or shared data is required in the whole project, such as a counter on a Web page. You can use the singleton mode to maintain the value of the counter without recording each refresh in the database and ensure thread safety;
3. Creating an object consumes too many resources, such as accessing IO, database and other resources;
4. For the environment where a large number of static constants and static methods (such as tool classes) need to be defined, the singleton mode can be adopted (of course, it can also be directly declared as static).