某公司研发星球维护系统,请使用饿汉式单例模式的实现思想,设计编写地球类。
程序运行参考效果图如下:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| package me.feihong.single;
public class Earth { private Earth(){ } private static Earth earth=new Earth(); public static Earth getEarth(){ return earth; } }
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| package me.feihong.test;
import me.feihong.single.Earth;
public class test {
public static void main(String[] args) { System.out.println("第一个地球创建中。。。。"); Earth one=Earth.getEarth(); System.out.println("第二个地球创建中。。。。"); Earth two=Earth.getEarth(); System.out.println("第三个地球创建中。。。。"); Earth three=Earth.getEarth(); System.out.println("问:三个地球是同一个么?"); System.out.println(one.getEarth()); System.out.println(two.getEarth()); System.out.println(three.getEarth()); }
}
|
输出结果:
1 2 3 4 5 6 7
| 第一个地球创建中。。。。 第二个地球创建中。。。。 第三个地球创建中。。。。 问:三个地球是同一个么? me.feihong.single.Earth@15db9742 me.feihong.single.Earth@15db9742 me.feihong.single.Earth@15db9742
|
请使用懒汉式单例模式的实现思想,设计编写皇帝类。
程序运行参考效果图如下:

任务
实现步骤:
1、定义私有构造方法
2、定义私有静态类对象
3、定义公有静态方法返回类内的私有静态对象,结合判断实现对象实例化
4、编写测试类,结合注释完成测试单例的皇帝类信息,程序效果参考运行效果图(具体对象引用信息不限)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| package me.feihong.king;
public class Emperor { private Emperor() { }
private static Emperor instance=null;
public static Emperor getInstance() { if(instance==null) instance=new Emperor(); return instance; }
}
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| package me.feihong.king;
public class EmperorTest {
public static void main(String[] args) { System.out.println("创建1号皇帝对象"); Emperor one=Emperor.getInstance(); System.out.println("创建2号皇帝对象"); Emperor two=Emperor.getInstance(); System.out.println("创建3号皇帝对象"); Emperor three=Emperor.getInstance(); System.out.println("三个皇帝对象依次是:"); System.out.println(one); System.out.println(two); System.out.println(three);
}
}
|