一、选择
1.单例模式的实现必须满足()个条件(多选) ACD
A. 类中的构造方法的访问权限必须设置为私有的
B. 类中的构造方法必须用protected修饰
C. 必须在类中创建该类的静态私有对象
D. 在类中提供一个公有的静态方法用于创建、获取静态私有对象
2.下列关于懒汉式和饿汉式的说法错误的是(多选) AB
A. 饿汉式在第一次使用时进行实例化
B. 懒汉式在类加载时就创建实例
C. 饿汉式的线程是安全的
D. 懒汉式存在线程风险
二、编程
某公司研发星球维护系统,请使用饿汉式单例模式的实现思想,设计编写地球类。
程序运行参考效果图如下:
public class Earth {
private Earth(){
System.out.println("地球诞生");
}
private static Earth instance = new Earth();
public static Earth getInstance(){
return instance;
}
}
public class TestEarth {
public static void main(String[] args) {
System.out.println("第一个地球创建中。。。。");
Earth earth1 = Earth.getInstance();
System.out.println("第二个地球创建中。。。。");
Earth earth2 = Earth.getInstance();
System.out.println("第三个地球创建中。。。。");
Earth earth3 = Earth.getInstance();
System.out.println("问:三个地球是同一个么?");
System.out.println(earth1);
System.out.println(earth2);
System.out.println(earth3);
}
}