//懒汉模式
public class Singleton {
private static Singleton instance;
/**
* 私有化构造方法
*/
private Singleton(){
}
public static Singleton getInstance(){
if (instance == null){
instance = new Singleton();
}
return instance;
}
public static void main(String[] args) {
Singleton s1 = Singleton.getInstance();
Singleton s2 = Singleton.getInstance();
System.out.println(s1==s2);
}
}
//饿汉模式
public class Singleton {
private static Singleton instance = new Singleton();
/**
* 私有化构造方法
*/
private Singleton(){
}
public static Singleton getInstance(){
return instance;
}
public static void main(String[] args) {
Singleton s1 = Singleton.getInstance();
Singleton s2 = Singleton.getInstance();
System.out.println(s1==s2);
}
}