单例模式(饿汉式/懒汉式demo)
/**
* 此文用于演示单例设计模式的实现
*
* 分析:
*
* 1、不要任意的在其他类中调用构造方法
*
* 构造方法私有化
* 2、本类中创建 一个该类的对象
*
* 3、向外暴露此对象
*
* public static 修饰符修饰 该对象
* 可以通过类名直接调用
*
*/
public class TestSingle {
public static void main(String[] args) {
SingleDemo d = new SingleDemo();
SingleDemo d2 = new SingleDemo();
SingleDemo2 sd1 = SingleDemo2.getInstance();
SingleDemo2 sd2 = SingleDemo2.getInstance();
System.out.println(sd1==sd2);
}
}
/**
* 饿汉式:类一加载 就要创建对象
*
* 【理解】 创建对象 的语句 看成 生活中 做饭、做菜 、吃饭
*/
class SingleDemo{
private static SingleDemo d = new SingleDemo();
public static SingleDemo getD() {
return d;
}
private SingleDemo(){
}
}
class Single {
private Single() {
}
private static Single single = null;
public static Single getInstance() {
if (single==null) {
synchronized (Single.class) {
if (single == null) {
single = new Single();
}
}
}
return single;
}
}