您的位置:首页 > 其它

Singleton Pattern

2016-07-23 05:18 357 查看
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;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: