Singleton Design Pattern
Singleton
类称为单例类,通过使用private
的构造函数确保了在一个应用中只产生一个实例,并且是自行实例化的(在Singleton
中自己使用new Singleton()
)。
public class Singleton {
private static final Singleton INSTANCE = new Singleton();
// 防止产生多个对象
private Singleton() {
}
// 通过该方法生成实例对象
public static Singleton getInstance() {
return INSTANCE;
}
// 尽量是static
public static void doSomething() {
}
}
public class Singleton {
private static Singleton instance = new Singleton();
private Singleton() {
}
private static Singleton getInstance() {
}
}
public class Singleton {
private static Singleton instance = new Singleton();
private Singleton() {
}
private static Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
public class Singleton {
private static Singleton instance;
private Singleton (){
}
public synchronized static Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
public class Singleton {
private volatile static Singleton instance;
private Singleton (){
}
public synchronized static Singleton getInstance() {
if (instance == null) {
synchronized(Singleton.class) {
if (instance == null) {
instance = new Singleton();
}
}
}
return instance;
}
}