单例设计模式分为两种:
- 在类被加载时初始化对象,称为SingletonPattern
- 在类被使用时初始化对象(延迟加载),称为LazySingletonPattern
SingletonPattern
public class C09_SingletonPattern {
private C09_SingletonPattern(){
System.out.println("C09_SingletonPattern was created...");
}
//类被加载时创建实例
private static C09_SingletonPattern instant = new C09_SingletonPattern();
public static C09_SingletonPattern getInstant(){
return instant;
}
//用于加速加载该类
public static void load(){}
}
LazySingletonPattern
public class C10_LazySingletonPattern {
private C10_LazySingletonPattern(){}
private static class SingletonPatternHolder{
private static C10_LazySingletonPattern instant = new C10_LazySingletonPattern();
}
public static C10_LazySingletonPattern getInstant(){
return SingletonPatternHolder.instant;
}
}