Java单例设计模式
单例设计模式是怎么来的
- private static定义变量和方法只能通过类名调用使用,可以看做是所有类都必须要做的事情,而对象无法使用,对象无权选择或者不选择。这就衍生出了一种设计模式:单例设计模式
单例设计模式怎么用?
- 单例设计模式用static来保证某一类只可new一次的机会,而且不提供对外new的方法,既不提供new的方式,只提供对外操作的方法。即保证一个类仅有一个实例,无法克隆,并提供一个访问它的全局访问点。
通过以下实例来深入理解单例设计模式的应用
public class Earth {
// new一个新地球只有Earth类可以调用
private static Earth earthInstance = new Earth();
// 无参构造器,保证外部无法new新的Earth
private Earth() {
}
// 提供Earth的全局访问点
public static Earth getEarthInstance() {
return earthInstance;
}
public void show showMessage() {
System.out.println("Hello,This is Earth");
}
}
public class main {
public static void main(String[] args) {
// 不合法的构造函数
// 编译时错误,构造函数 Earth() 是不可见的
// Earth earth = new Earth();
// 获取唯一可用对象
Earth earth = Earth.getEarthIntance();
// 显示信息
earth.showMessage();
}
}
打印结果如下:
"Hello,This is Earth"
// 在Java基础API部分,通过查看底层实现代码,可发现Calendar(日期类)使用此设计模式,下方演示。
import java.util.*;
public class main {
public static void main(String[] args) {
Calendar calendar = Calendar.getInstance();
// 打印当前时间
System.out.println(calendar.getTime());
int year = calendar.get(Calendar.YEAR);
// 打印当前年份
System.out.println("year = " + year);
}
}
打印结果如下:
Mon Apr 18 09:08:52 CST 2022
year = 2022