1.写一个单子设计模
//饿汉式
class Singleton1
{
//2. 类的内部创建对象
private static Singleton1 instance = new Singleton1();
//1. 私有化构造器
private Singleton1(){}
public static Singleton1 getInstance(){
return instance;
}
}
//懒汉式
class Singleton2
{
//2. 类的内部创建对象
private static Singleton2 instance = null;
//1. 私有化构造器
private Singleton2(){}
public static Singleton2 getInstance(){
if(instance == null){
instance = new Singleton2();
}
return instance;
}
}
class Singleton {
public static void main(String[] args){
Singleton1 s1 = Singleton1.getInstance();
Singleton1 s2 = Singleton1.getInstance();
System.out.println(s1 == s2);
}
}