代码如下:
//单例模式
//instance--实例
//该篇中记录了饿汉模式和懒汉模式
public class HungryMan {
public static void main(String[] args) {
Single01.say();
Single02.say();
}
}
class Single01{
//只能有instance这一个实例。
private Single01(){
System.out.println("01created");
};
//private static Single01(){};
private static Single01 instance = new Single01();
public static Single01 getInstance(){
return instance;
}
public static void say(){
System.out.println("hello!");
}
}
class Single02{
private Single02(){
System.out.println("02created");
}
private static Single02 instance = null;
public static Single02 getInstance(){
if(instance==null){
instance = new Single02();
}
return instance;
}
public static void say(){
System.out.println("HELLO!");
}
}
两者区别如下: