One of the simplest design patterns used in Android development, especially one that was often asked in the initial interview:
Article Two: Singleton mode
Singleton mode is available when you need to control only one instance of a class, and the customer can only access it from one global access point.
There are two types of singleton mode: a hungry man type and lazy type .
1, a hungry man type:
Package com.hongri.singletonpattern;/** * Singleton mode: * A hungry man (a hungry man is thread-safe) * @author Zhongyao */public class Singleton2 {private STA Tic Singleton2 uniqueinstance = new Singleton2 ();/** * Private Constructor Method */private Singleton2 () {};p ublic static Singleton2 Getinstanc E () {return uniqueinstance;};}
2, lazy type:
The double dashed line up and down respectively is optimized the different lazy type realization form, may choose according to the need.
Package com.hongri.singletonpattern;/** * Singleton mode: * Lazy (non-synchronized lazy is thread insecure) * @author Zhongyao */public class Singleton {privat e static Singleton uniqueinstance = null;/** * Private constructor Method */private Singleton () {};/** * is thread-safe, but reduces the speed of the entire access * @return */PUBL IC Static synchronized Singleton getinstance () {if (uniqueinstance = = null) {uniqueinstance = new Singleton ();} return uniqueinstance;} =================================================================/** * "Double check plus lock": both thread-safe and performance-not-to-be-impact */// Add a volatile modifier to a variable that holds an instance private volatile static Singleton uniqueinstance = Null;private Singleton () {}public static Singleton getinstance () {///checks if the instance exists before entering the following sync block if it is not present (uniqueinstance = = null) {//sync block, thread-safe creation instance synchronized ( Singleton.class) {//Check again if the instance exists, if it does not exist to actually create the instance if (uniqueinstance = = null) {uniqueinstance = new Singleton ()}}} return uniqueinstance;}}
A single-instance pattern of Java design patterns