in many design patterns, I believe that most of the first design patterns of ape-in-the-box contact are single-case patterns, of course, I am no exception. The singleton pattern 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. Singleton mode provides an object in the whole system, and then the whole system uses this object, which is the purpose of the single case.
One, full-han type single case:
public class Singleton { /** * Singleton object instance * / private static Singleton instance = null; public static Singleton getinstance () { if (instance = = null) { instance = new Singleton (); } return instance; } }
Two, a hungry man type single case:
public class Singleton { /** * Singleton object instance * /private static Singleton instance = new Singleton (); public static Singleton getinstance () { return instance; } }
These two kinds of singleton in the actual code, often can not meet the requirements, which requires us to adapt to their own needs to rewrite these singleton patterns,
For example, if you create a singleton object that requires additional parameters, this time we need to rewrite it:
public class Singleton { /** * Singleton object instance * / private static Singleton instance = null; public static Singleton getinstance (context context) { if (instance = = null) { instance = new Singleton (CO ntext); } return instance;} }
For example:In the case of resource sharing, multi-threaded concurrent access must be met, and this is what we should do:
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 the conditions, no matter how the change, are the two variants of the single-CASE model!!!!
Android design mode (1)----Single-case mode