首页 > 其他 > 详细

单例模式

时间:2016-09-06 15:48:21      阅读:209      评论:0      收藏:0      [点我收藏+]

参考:http://my.oschina.net/suyewanwan/blog/102525

1.懒汉式:

public class Singleton {
    private static Singleton singleton;
    private Singleton() {}  //此类不能被实例化
    public static synchronized Singleton getInstance() {
        if (singleton == null) {
            singleton = new Singleton();
        }
        return singleton;
    }
}


2.饿汉式:
public class Singleton {
    private static final Singleton SINGLETON = new Singleton();
    private Singleton() {}  //此类不能被实例化
    public static Singleton getInstance() {
        return SINGLETON;
    }
}


3.内部类单例模式:
public class Singleton {
    private Singleton() {} //构造方法是私有的,从而避免外界利用构造方法直接创建任意多实例。
    public static Singleton getInstance() {
        return Holder.SINGLETON;
    }
    private static class Holder {
       private static final Singleton SINGLETON = new Singleton();
    }
}

单例模式

原文:http://www.cnblogs.com/shuo1208/p/5845787.html

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