- 概念:单例对象的类必须保证只有一个实例存在
- 两种实现:
第一种
/*** 饿汉式(推荐)* 单例实例在类装载时就构建,急切初始化*/public class Test {private Test() {}public static Test instance = new Test();public Test getInstance() {return instance;}}第二种public class SpecialSingleton {
// 静态内部类private static class NestClass {private static SpecialSingleton instance;static {System.out.println("instance = new SingletonTest()");instance = new SpecialSingleton();}
}
// 不能直接newprivate SpecialSingleton() {System.out.println("private SingletonTest()");}public static SpecialSingleton getInstance() {System.out.println("SingletonTest getInstance()");return NestClass.instance;}public static void main(String[] args) {SpecialSingleton instance = SpecialSingleton.getInstance();System.out.println("========================================");}
}