preface

When learning Java design patterns, the first pattern to learn is the singleton pattern, refer to the book “Zen of Design Patterns” 2nd edition, here make a record and learning experience, easy to review later. Sorted out the latest Java core knowledge points in 2021, interview topics and the latest Internet real questions in 21 years.

Tip: The following is the body of this article, the following cases for reference

1. Illustrate the singleton pattern

In ancient times, when everyone talked about the emperor, everyone knew who was referring to, there was no need to add a specific name in front of the emperor. This process is reflected in the design world, which requires that a class generate only one emperor, on which all objects depend the same. This scenario is then implemented programmatically

1. Program code

①, the emperor class

Private static final Emperor = new Emperor(); private static final Emperor = new Emperor(); Private Emperor(){} private Emperor(){} public static Emperor getInstance(){return emperor; } public static void say(){system.out.println (" I am the king "); }}Copy the code

By defining a private access constructor, Emperor can avoid having an object new by another class. Instead, Emperor can create an object by himself. Any other class that accesses the class can get the same object through getInstance().

②, subject class

Public class Minister {public static void main(String[] args) {public class Minister {public static void main(String[] args) { day < 3; Day++) {/ / record courtiers which heaven dynasty emperor worship System. Out. The println (" < -- -- -- -- -- -- -- -- the first "+ (day + 1) +" toward the sky -- -- -- -- -- -- -- -- > "); Println (" Long live the emperor! Long live the emperor! "); Emperor Emperor = Emperor.getInstance(); Emperor. Say (); }}}Copy the code

③ Operation results

Definition of singleton pattern

Singleton mode:

Ensure a class has only one instance, and provide a global point of access to it. The singleton pattern is a creative type design pattern

1. General class diagram of singleton pattern

Class diagram parsing:

The Single class is a Singleton class, which ensures that only one instance is generated in an application by using the private constructor (objects of that class cannot be instantiated in other classes using the new keyword), and instantiates itself in the Singleton class

Self-instantiating code:

private static final Singleton singleton = new Singleton(); Private static final Singleton = new private static final Singleton = new private static final Singleton = new private static final Singleton = new Singleton(); Private Singleton(){} public static Singleton getSingleton(){return public static Singleton getSingleton(){return  singleton; Static public static void doSomething(){}}Copy the code

The application of singleton pattern

1. Advantages of singleton pattern

The singleton pattern has only one instance in memory, thus reducing memory overhead, especially when an object needs to be created and destroyed frequently and performance cannot be optimized for creation or destruction.

Since the singleton value generates an instance, the performance overhead of the system is greatly reduced. When the generation of an object requires more resources, such as reading configuration and generating other dependent objects, the system can directly generate a singleton object 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 JavaEE).

The singleton mode can avoid multiple resource usage. For example, when a file is being written, only one instance exists in the memory. Therefore, after a resource file is locked, simultaneous write operations on the same resource file can be 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 to be responsible for all data table mapping processing.

2. Disadvantages of singleton pattern

The singleton pattern is generally not an interface, so it is difficult to extend, and if you do, there is basically no other way to do it than to modify the code in the original class. This violates the open closed principle (open for extensions, closed for modifications). You can extend code from a class, but you can’t modify the original code. One question to note here: Why are singletons not interfaces in general? A: Because in the singleton pattern, you are required to instantiate and provide a single instance, whereas interfaces and abstract classes cannot be instantiated, so interfaces and abstract classes make no sense to the singleton pattern.

The singleton pattern is not test friendly. In a parallel development environment, you cannot test until the singleton pattern is complete.

The singleton pattern conflicts with the single responsibility principle. In the Java design pattern, a class should implement only one logic, while the singleton pattern combines multiple business logic in a single class, so whether to adopt the singleton pattern depends on the actual environment.

3. Usage scenarios of singleton pattern

Typically in a system, some classes are required to have one and only one object. The singleton pattern can be used when more than one object can cause unnecessary problems

An environment that requires the generation of a unique sequence number

You need a shared access point or shared data throughout the project, such as a counter on a front-end page, which does not need to log every refresh to the database, and uses a singleton pattern to hold the value of the counter, which also ensures that the thread is safe.

Creating an object consumes too many resources. For example, to access IO and database resources, you can use the singleton mode if you need to define a large number of static constants and static methods. For example, you can use the singleton mode if you need to define a large number of tool classes

4. Notes for singleton mode

Thread-unsafe lazy singleton pattern

In the case of non-high concurrency (low concurrency), the singleton pattern does not have the problem of generating multiple instances. However, in the case of high concurrency, using the singleton pattern requires consideration of process synchronization.

For example:

Private static Singleton = new Singleton(); private static Singleton = new Singleton(); Private Singleton(){} public static Singleton getSingleton(){if (singleton == null){ singleton = new Singleton(); } return singleton; }}Copy the code

In this singleton code, there is a danger if there is high concurrency.

if (singleton == null){
	singleton = new Singleton();
}
Copy the code

The reason:

Singleton = new Singleton(); singleton = new Singleton(); singleton = new Singleton(); So thread B’s judgment condition is also true, and the singleton doesn’t exist yet, so we keep going, thread A and thread B both get an object, and we have two objects in memory.

Therefore, in order to solve this thread unsafe situation, the getSingleton method can be preceded by the synchronized keyword, or can be implemented by adding the synchronized keyword inside the getSingleton method.

Therefore, there are two kinds of singleton patterns for multithreading safety: lazy singleton pattern and hungry singleton pattern

Thread-safe lazy singleton pattern

Private static Singleton = new Singleton(); private static Singleton = new Singleton(); Private synchronized Singleton(){} public static synchronized Singleton(){} public static synchronized Singleton() getSingleton(){ if (singleton == null){ singleton = new Singleton(); } return singleton; Static public static void doSomething(){}}Copy the code

As mentioned earlier in the solution to multi-threading, the multi-thread safe lazy singleton avoids the problem of creating multiple objects in memory by locking them. Therefore, the lazy singleton thread is safe and is initialized only at the first call, thus avoiding memory waste. However, lazy singleton mode must be synchronized to ensure singleton, but locking will affect efficiency.

(3) Hanhan-style singleton mode

Private static Singleton = new Singleton(); private static Singleton = new Singleton(); Private Singleton(){} public static Singleton getSingleton(){return public static Singleton getSingleton(){return  singleton; Static public static void doSomething(){}}Copy the code

Hanky-hank singletons are initialized when the class is loaded, wasting memory. On the contrary, because the hunchman singleton is not locked, the execution efficiency is improved.

④ Comparison between slacker singleton pattern and hungry singleton pattern

conclusion

This is the first singleton of the Java design patterns, one of the simpler of the 23 patterns and one of the most widely used. In Spring, for example, each Bean is a singleton by default, which sort of means that the Spring container can manage the declaration cycle of these beans and decide freely when the Bean is created, when the Bean is destroyed, and what happens when it is destroyed.

I have compiled a 2021 latest Java core knowledge, interview topics and 21 years of the latest Internet real questions, e-books and other Spring series of family, Java systematic information, friends who need to pay attention to the public number [procedure yuan small] can be obtained.