单例模式保证一个类只有一个实例,并提供唯一一个访问实例的方法。
1.饿汉式(线程安全):
public class Singleton {
private final static Singleton instance = new Singleton();
private Singleton(){}
public static Singleton getInstance(){
return instance;
}
}
2.懒汉式(线程安全,但是使用了同步锁):
public class Singleton {
private static Singleton instance;
private Singleton() {}
public static synchronized Singleton getInstance() {
if (singleton == null) {
instance = new Singleton();
}
return instance;
}
}
3.静态内部类
public class Singleton {
private Singleton() {}
private static class InnerSingleton{
private static final Singleton instance = new Singleton();
}
public static Singleton getInstance() {
return InnerSingleton.instance;
}
}
网友评论