六种线程安全的单例模式

单例模式怕是很多程序员使用最多的设计模式了,面向对象的23种设计模式点这里。废话不多说,直接上代码:

public class Singleton {  //1.懒汉型
    private static Singleton instance;  
    private Singleton (){}  
    public static synchronized Singleton getInstance() {  
    if (instance == null) {  
        instance = new Singleton();  
    }  
    return instance;  
    }  
}  
public class Singleton {  //2.饿汉型
    private static Singleton instance = new Singleton();  
    private Singleton (){}  
    public static Singleton getInstance() {  
    return instance;  
    }  
} 
public class Singleton {  //3.内部类型,可看做饿汉变种
    private static class SingletonHolder {  
    private static final Singleton INSTANCE = new Singleton();  
    }  
    private Singleton (){}  
    public static final Singleton getInstance() {  
    return SingletonHolder.INSTANCE;  
    }  
}  
public class Singleton {  //4.双重校验锁,1.5以后可用
    private static Singleton singleton;  
    private Singleton (){}  
    public static Singleton getSingleton() {  
    if (singleton == null) {  
        synchronized (Singleton.class) {  
        if (singleton == null) {  
            singleton = new Singleton();  
        }  
        }  
    }  
    return singleton;  
    }  
}  
public enum Singleton {  //5.枚举型,Effective Java作者提倡的。可防止反序列化
    INSTANCE;  
    public void whateverMethod() {  
    }  
}  
public class Singleton {  //6.静态型,全部静态方法和属性
    private Singleton (){}  
    public static void whateverMethod() {  
    }  
}  

现在有六种,那么推荐哪一种呢。其实我个人比较懒,所以推荐5和6这种字少的。6呢可以继承,但重写方法就违反了里氏替换原则,所以继承的时候要记得只采取不同的子类扩展不同的方法。

你可能感兴趣的:(java,设计模式详解)