首页 > 其他 > 详细

[GOF] Singleton

时间:2014-03-07 01:02:04      阅读:489      评论:0      收藏:0      [点我收藏+]

单例实现方式:

  • bubuko.com,布布扣Use enum which is recommended by Josh Bloch, the author of Effective Java.

public enum Singleton {
    INSTANCE;
    public String hello() {
        return "hello";
    }
}


  • 饿汉

public class Singleton {
    private static final Singleton INSTANCE = new Singleton();
    private Singleton() {
    }
    public static Singleton getInstance() {
        return INSTANCE;
    }
}


  • 懒汉 Double-checked Locking, since Java 5

public class Singleton {
    private volatile static Singleton instance;
    private Singleton() {
    }
    public static Singleton getInstance() {
        if (instance == null) {
            synchronized (Singleton.class) {
                if (instance == null) {
                    instance = new Singleton();
                }
            }
        }
        return instance;
    }
}


本文出自 “ZenMaster” 博客,请务必保留此出处http://nealfu.blog.51cto.com/8652301/1369350

[GOF] Singleton,布布扣,bubuko.com

[GOF] Singleton

原文:http://nealfu.blog.51cto.com/8652301/1369350

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!