Android development design pattern (1, Singleton (singleton mode))

Generally speaking, design patterns in Java can be divided into three types: creational patterns, structural patterns and behavioral patterns.


Let’s talk about the creation model today


There are five creational modes: singleton mode, factory method mode, abstract factory mode, builder mode, and prototype mode.


One, Singleton (singleton mode)

Singleton mode: It can guarantee that there is only one instance of a class, and it can instantiate and provide this instance to the entire system.

In a computer system, the driver objects of thread pool, serial port, cache, log object, dialog box, printer, and graphics card are often designed as singletons. These applications more or less have the function of a resource manager. The singleton mode can be implemented in several different ways.

(1) Lazy man-style singleton mode

// SingletonOne.java

public class SingletonOne {

      private static SingletonOne singleton = null;

      private SingletonOne(){}

      public static SingletonOne getInstance(){

             if(singleton == null){

                    singleton= new SingletonOne();

              }

             returnsingleton;

      }

}

The singleton mode is not thread-safe, and may not cause problems in the case of low concurrency, but in the case of high concurrency, multiple instances may appear in the system. For example: there are two threads, the first thread has executed singleton = newSingletonOne(), but the object has not yet been obtained (the object is being initialized, and initialization takes a certain amount of time), then the second thread has executed if (singleton = = null), then the if condition of the second thread is also established, so that the two threads each obtain an object, resulting in two objects in the memory.

In order to solve the thread safety problem, you can modify the lazy mode, add the synchronized keyword before the getInstance method, or use the synchronized keyword inside the method, but this is not the best singleton mode.

(2) Hungry Chinese singleton mode

The best singleton pattern:

// SingletonTwo.java

public class SingletonTwo {

      private static final SingletonTwo singleton = new SingletonTwo();

      private SingletonTwo(){}

      public static SingletonTwo getInstance(){

              returnsingleton;

      }

}

The hungry man singleton mode is to create a static object for system use at the same time as the class is created, and it will not change in the future, so it is thread-safe.




Guess you like

Origin blog.csdn.net/xhf_123/article/details/49837197