单例模式:保证一个类仅有一个实例,并提供一个访问她的全局访问点。
有懒汉式与饿汉式之分:
1.懒汉式:
public class Singleton {
private static Singleton instance = null;
private Singleton() {
}
public static synchronized Singleton getInstance() {
if(instance == null) {
synchronized(synchronized.class) {
if(instance == null) {
instance = new Singleton();
}
}
}
return instance;
}
}
2.饿汉式:
public class Singleton {
private static Singleton instance = new Singleton();
private Singleton() {
}
public static Singleton getInstance() {
return instance;
}
}
有懒汉式与饿汉式之分:
1.懒汉式:
public class Singleton {
private static Singleton instance = null;
private Singleton() {
}
public static synchronized Singleton getInstance() {
if(instance == null) {
synchronized(synchronized.class) {
if(instance == null) {
instance = new Singleton();
}
}
}
return instance;
}
}
2.饿汉式:
public class Singleton {
private static Singleton instance = new Singleton();
private Singleton() {
}
public static Singleton getInstance() {
return instance;
}
}