单例设计模式是最好理解的一种设计模式,分别为懒汉式和饿汉式。
饿汉式:
public class Singleton {
// 直接创建对象
public static Singleton instance = new Singleton();
// 私有化结构函数
private Singleton() {
}
// 返回对象实例
public static Singleton getInstance() {
return instance;
}
}
懒汉式:
public class Singleton {
// 声明变量
private static volatile Singleton singleton = null;
// 私有构造函数
private Singleton() {
}
// 提供对外方法
public static Singleton getInstance() {
if (singleton == null) {
synchronized (Singleton.class) {
if (singleton == null) {
singleton = new Singleton();
}
}
}
return singleton;
}
}