实现单例模式

1. 只适用单线程
class Singleton {
private static Singleton instance;
private Singleton() {
}
public static Singleton getInstance() {
if(instance == null) {
instance = new Singleton();
}
return instance;
}
}
2. 多线程
class Singleton {
private static Singleton instance;
private Singleton() {
}
public synchronized static Singleton getInstance() {
if(instance == null) {
instance = new Singleton();
}
return instance;
}
}
3. 类内加载
class Singleton {
private static Singleton instance = new Singleton();
private Singleton() {
}
public  static Singleton getInstance() {
return instance;
}
}
4. 双重校验锁
class Singleton {
private static Singleton instance;
private Singleton() {
}
public  static Singleton getInstance() {
if(instance ==null) {
synchronized(Singleton.class) {
if(instance == null) {
instance = new Singleton();
}
}
}
return instance;
}
}

你可能感兴趣的:(实现单例模式)