Rah*_*ogi 6 java singleton static static-block lazy-initialization
以下是实现单例的两种方法.各有哪些优缺点?
静态初始化:
class Singleton {
private Singleton instance;
static {
instance = new Singleton();
}
public Singleton getInstance() {
return instance;
}
}
Run Code Online (Sandbox Code Playgroud)
延迟初始化是:
class Singleton {
private Singleton instance;
public Singleton getInstance(){
if (instance == null) instance = new Singleton();
return instance;
}
}
Run Code Online (Sandbox Code Playgroud)
小智 9
同步访问器
public class Singleton {
private static Singleton instance;
public static synchronized Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
Run Code Online (Sandbox Code Playgroud)
双重检查锁定和易失性
public class Singleton {
private static volatile Singleton instance;
public static Singleton getInstance() {
Singleton localInstance = instance;
if (localInstance == null) {
synchronized (Singleton.class) {
localInstance = instance;
if (localInstance == null) {
instance = localInstance = new Singleton();
}
}
}
return localInstance;
}
}
Run Code Online (Sandbox Code Playgroud)
按需持有人的习语
public class Singleton {
public static class SingletonHolder {
public static final Singleton HOLDER_INSTANCE = new Singleton();
}
public static Singleton getInstance() {
return SingletonHolder.HOLDER_INSTANCE;
}
}
Run Code Online (Sandbox Code Playgroud)
小智 5
第一个是急切的初始化.急切初始化甚至在使用它之前就会创建实例,这不是最佳实践.
第二个是懒惰初始化.惰性实现在单线程环境中运行良好,但是当涉及多线程系统时,如果多个线程同时位于if循环内,则会导致问题.它将破坏单例模式,两个线程将获得单例类的不同实例.
请访问:http://www.journaldev.com/1377/java-singleton-design-pattern-best-practices-with-examples#static-block-initialization了解更多信息
| 归档时间: |
|
| 查看次数: |
3565 次 |
| 最近记录: |