码迷,mamicode.com
首页 > 其他好文 > 详细

单例模式

时间:2016-09-06 15:49:47      阅读:147      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!