Design mode:
The most effective way to solve a class of problems, 23 design patterns in Java.
Singleton design Mode (Singleton): Resolves a class that only has one object in memory
For example, when you use the same configuration information object for multiple programs, you need to guarantee the uniqueness of the object.
To ensure that the object is unique:
In order to avoid the creation of such objects by other programs, it is forbidden to establish such objects by other programs;
It is also necessary to customize an object in this class in order for other programs to have access to that class object;
In order to facilitate the access of other programs to custom objects, some access methods can be provided externally;
The A Hungry man style of single case design pattern
Single class into the memory, has created a good object, simply said to eat on the first.
Ideas:
Privatization of the constructor function;
Create an object of this class in the class;
Provides a public access method that can be obtained to the class object;
Steps:
Privatize a constructor
Private single () {}
Create an object of this class in the class (the final keyword, etc. have learned, is the ultimate meaning, hehe)
Private Finla Static single =new single ();
Provides a public access method that can be obtained to the class object
public static single getinstance () {
return single;
}
The lazy type of the single case design pattern
object is initialized when the method is called, or deferred loading of the object
Single class into memory, the object does not exist, only the object is established when the GetInstance method is called.
Steps:
Private single () {}
private static single =null;
public static single getinstance () {
if (single==null) {
Synchronized (Single.class) {
if (single==null)
Single =new single ();
}
}
return single;
}
Why are there a hungry man and lazy-style?
The reason is that the interview, because the interview is a lazy, because to take into account the multi-threaded security issues, so that the program more rigorous.
The actual development uses the A hungry man type, because in the consideration multi-threading will be more secure, the lazy type solves the security question method, the double judgment, joins the lock.
Summarize:
A hungry man: Initializes the object as soon as it comes up.
Waste a little bit of memory, because you do not call it.
Lazy: When an object invokes a method, it is initialized, also called the object's inertia load.
A little bit of memory is saved, because only the call takes up memory.
A single-instance design pattern for Java design patterns