For making the app operating influently,the developver of this app usually use the singleton pattern avoiding serious memory consumption.
a.private static Lazy singleton Eager singleton
b.Lazy Singleton (饿汉式单例模模式)- When define a static member variable,create an object of this class directly and assign it.
//Eager singleton
public class Singleton {
private static HttpOperation instance = new HttpOperation();
private HttpOperation(){
}
public static HttpOperation getInstance(){
return instance;
}
}
c.Eager Singleton (懒汉式单例模式)
//Lasy singleton
public class Singleton {
private static HttpOperation instance;
private HttpOperation(){
}
public static HttpOperation getInstance(){
// Make a judgement about whether this object has a value
if(instance = null){
// None,create an object with value
instance = new HttpOperation();
}
return instance;
}
}
The implementation Methods
1.Privatize all constructors.
2.Provide a static method to make externals(外部) gain the single 'private' instance object of this class.
3.Define a static variable to save this single object in this class.
4.Create an object.(Lazy singleton & Eager singleton)
But we still have to take the thread safety into account.For there may exist more than one thread access this method and create more than two instances.
synchronized(HttpOperation.class){} -- unlatch(Lock)
Every class onws only one lock
This is how we lock it for safety.
//Lasy singleton
public class Singleton {
private static HttpOperation instance;
private HttpOperation(){
}
public static HttpOperation getInstance(){
// Make a judgement about whether this object has a value
if(instance == null){
synchronized(HttpOperation.class){
if(instance == null){
// None,create an object with value
instance = new HttpOperation();
}
}
}
return instance;
}
}