Java单例模式
Java单例模式
1、使用同步方法:
private static Singleton instance; public static synchronized Singleton getInstance() { if (instance == null) instance == new Singleton(); return instance; }
2、放弃同步,使用静态变量:
private static Singleton instance = new Singleton();
public static Singleton getInstance(){
return instance;
}
3、比较新颖的写法:
public class Singleton {
static class SingletonHolder {
static Singleton instance = new Singleton();
}
public static Singleton getInstance() {
return SingletonHolder.instance;
}
}
评论暂时关闭