Single-Case mode:
1: Lazy Type
Package com.design;
/* 1: Lazy type */
public class Singleton {
/**
* Private, do not allow instances to be obtained externally through singleton.instance
* Static method can only access static variables.
*/
private static Singleton instance;
Private, not allowed to instantiate externally
Private Singleton () {}
/**
* Multithreading calls this method, it is possible to create more than one instance, need to synchronize, but pay attention to the efficiency problem
* 1.instance is empty the code fragment that needs to create the object needs to be locked, i.e. @0
* 2. The code snippet for creating the object must be judged again (
* If A and B threads, A and B both enter @1, a gets the lock, and executes the code that created the object,
* then B gets the lock again, and if you don't add @2, create an instance.
* )
*
*/
public static Singleton getinstance () {
if (instance = = null) {//@0
@1
Synchronized (Singleton.class) {
if (instance = = null) {//@2
Instance = new Singleton ();
}
return instance;
}
}
return instance;
}
}
2. A Hungry man type:
Package com.design1;
/* 2: A hungry man type */
public class Singleton {
private static Singleton instance = new Singleton ();
Private Singleton () {}
private static Singleton getinstance () {
return instance;
}
}
Java common Design Patterns-Singleton mode