Singleton Pattern:
1. Early mode
public class President{
private static President instance = new President();
private President() {}
public static President getInstance() {
return instance;
}
}
2. Lazy mode:
public class President{
private static President instance;
private President() {}
public static synchronized President getInstance() {
if(instace == null){
instance = new President();
}
return instance;
}
}
3. Optimize solution: (double checked locking)
public class President{
private static volatile President instance;
private President() {}
public static President getInstance() {
if(instance == null) {
synchronized(President.class){
if(instance == null){
instance = new President();
}
}
}
return instance;
}
}