某公司研发星球维护系统,请使用饿汉式单例模式的实现思想,设计编写地球类。
程序运行参考效果图如下:
package me.feihong.single;
public class Earth {
//定义私有构造方法,并在构造方法中打印输出“地球诞生”
private Earth(){
}
//定义私有静态类对象并完成实例化
private static Earth earth=new Earth();
//定义公有静态方法返回类内的私有静态对象
public static Earth getEarth(){
return earth;
}
}
package me.feihong.test;
import me.feihong.single.Earth;
public class test {
public static void main(String[] args) {
// TODO Auto-generated method stub
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());
}
}
输出结果:
第一个地球创建中。。。。
第二个地球创建中。。。。
第三个地球创建中。。。。
问:三个地球是同一个么?
me.feihong.single.Earth@15db9742
me.feihong.single.Earth@15db9742
me.feihong.single.Earth@15db9742
请使用懒汉式单例模式的实现思想,设计编写皇帝类。
程序运行参考效果图如下:
任务
实现步骤:
1、定义私有构造方法
2、定义私有静态类对象
3、定义公有静态方法返回类内的私有静态对象,结合判断实现对象实例化
4、编写测试类,结合注释完成测试单例的皇帝类信息,程序效果参考运行效果图(具体对象引用信息不限)
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;
}
}
package me.feihong.king;
public class EmperorTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
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);
}
}