1.懒汉模式
//Singleton.java
public class Singleton {
//防止多次实例 new
private Singleton() {}
//保证线程安全(两个线程同时获取实例)
private static class SingletonInstance {
private static final Singleton INSTANCE = new Singleton();
}
//获取实例
public static Singleton getInstance() {
return SingletonInstance.INSTANCE;
}
}
//--------------QAQ---------------
//other.java
Singleton.getInstance()
2.饥汉模式(一)
//Singleton.java
public class Singleton {
private final static Singleton INSTANCE = new Singleton();
private Singleton(){}
public static Singleton getInstance(){
return INSTANCE;
}
}
//--------------QAQ---------------
//other.java
Singleton.getInstance()
3.饥汉模式(二)
//Singleton.java
public class Singleton {
public final static Singleton INSTANCE = new Singleton();
private Singleton(){}
}
//--------------QAQ---------------
//other.java
Singleton.INSTANCE
网友评论