设计模式 - 单例模式

来源:互联网 发布:windows pe 知乎 编辑:程序博客网 时间:2024/06/06 02:30
/** * 第一种(懒汉,线程不安全),缺点线程不安全 */class Singleton1 {    private static Singleton1 singleton1;    private Singleton1() {    }    public static Singleton1 getInstance() {        if (singleton1 == null) {            singleton1 = new Singleton1();            return singleton1;        } else {            return singleton1;        }    }}/** * 第二种(懒汉,线程安全),缺点效率很低 */class Singleton2 {    private static Singleton2 singleton2;    private Singleton2() {    }    public static synchronized Singleton2 getInstance() {        if (singleton2 == null) {            singleton2 = new Singleton2();            return singleton2;        } else {            return singleton2;        }    }}/** * 第三中(饿汉,线程安全),缺点不支持延迟加载,如果可以的话建议使用,不容易产生其他问题 */class Singleton3 {    private static Singleton3 singleton3 = new Singleton3();    private Singleton3() {    }    public static Singleton3 getInstance() {        return singleton3;    }}/** * 第四中(饿汉,变种),跟第三种类似,优点是在初始化类时可以添加其他操作 */class Singleton4 {    private static Singleton4 singleton4;    static {        singleton4 = new Singleton4();    }    private Singleton4() {    }    public static Singleton4 getInstance() {        return singleton4;    }}/** * 第五中(静态内部类),跟第三种类似,优点是在初始化类时不会初始化静态类 * 只有在调用时才进行初始化,在希望实现延迟加载时推荐使用该方法 */class Singleton5 {    private static class Singleton5Holder {        public static Singleton5 INSTANCE = new Singleton5();    }    private static Singleton5 singleton5;    private Singleton5() {    }    private Singleton5 getInstance() {        if (singleton5 == null) {            singleton5 = Singleton5Holder.INSTANCE;            return singleton5;        } else {            return singleton5;        }    }}/** * 第六中(枚举),推荐做法,不过很少见 */enum Singleton6 {    INSTANCE;    public void whateverMethod() {    }}/** * 第七中(双重检查锁定),只有在java1.5以上的版本可以使用,推荐使用静态内部类来实现 */class Singleton7 {    private volatile static Singleton7 singleton7;    private Singleton7() {    }    public static Singleton7 getInstance() {        if (singleton7 == null) {            synchronized (Singleton7.class) {                if (singleton7 == null) {                    singleton7 = new Singleton7();                }                return singleton7;            }        } else {            return singleton7;        }    }}/** * 单例模式还可以进行扩展,变为有上限的多例模式,具体方法可以类比静态类 */
0 0