一、概念
单例类,通过隐藏构造方法,在内部初始化一次,并提供一个全局访问点。
二、通用写法
饿汉式加载
publci class HungrySingleton() {
private static final Singleton instance = new Singleton();
private Singleton(){};
private static Singleton getInstance() {
return instance;
}
}
}
懒汉式加载
public class LazySimpleSingleton() {
private LazySingleton(){}
// 静态块,公共内存区域
private static LazySimpleSingleton lazy = null;
public static LazySimpleSingleton getInstance() {
if(lazy == null) {
lazy = new LazySimpleSigleTon();
}
return lazy;
}
}