Android design mode (1) ---- Singleton Mode
Among many design patterns, I believe that the design patterns most programmers first came into contact with are the singleton model. Of course, I am no exception. The Singleton mode should be the simplest of all design patterns. The Singleton mode is simple, but if you go deep into the singleton mode, it will involve a lot of knowledge. I will continue to update this article. The Singleton mode provides an object throughout the system, and then the entire system uses this object. This is the purpose of the singleton mode.
I. Full Chinese Style singleton:
Public class Singleton {/*** Singleton object instance */private static Singleton instance = null; public static Singleton getInstance () {if (instance = null) {instance = new Singleton ();} return instance ;}}
Ii. Hunger type singleton:
Public class Singleton {/*** Singleton object instance */private static Singleton instance = new Singleton (); public static Singleton getInstance () {return instance ;}}
These two Singleton models often fail to meet the requirements in actual code. Therefore, we need to rewrite these Singleton models according to our own needs,
For example, if other parameters are required for the created singleton object, we need to rewrite it as follows:
Public class Singleton {/*** Singleton object instance */private static Singleton instance = null; public static Singleton getInstance (Context context) {if (instance = null) {instance = new Singleton (context);} return instance ;}}
For example, in the case of resource sharing, multi-thread concurrent access is required. In this case, we should do this:
Public class Singleton {/*** Singleton object instance */private static Singleton instance = null; public synchronized static Singleton getInstance () {if (instance = null) {instance = new Singleton ();} return instance ;}}
In fact, no matter what conditions, no matter how you change it, it is a variant of the two Singleton modes !!!!