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

单例模式

时间:2015-08-25 23:50:50      阅读:169      评论:0      收藏:0      [点我收藏+]

标签:

饿汉式(常用)

public class EagerSingleton {
    private static EagerSingleton instance = new EagerSingleton();
    /**
     * 私有默认构造子
     */
    private EagerSingleton(){}
    /**
     * 静态工厂方法
     */
    public static EagerSingleton getInstance(){
        return instance;
    }
}

懒汉式

public class LazySingleton {
    private static LazySingleton instance = null;
    /**
     * 私有默认构造子
     */
    private LazySingleton(){}
    /**
     * 静态工厂方法
     */
    public static synchronized LazySingleton getInstance(){
        if(instance == null){
            instance = new LazySingleton();
        }
        return instance;
    }
}

版权声明:本文为博主原创文章,未经博主允许不得转载。

单例模式

标签:

原文地址:http://blog.csdn.net/qqyanjiang/article/details/47985039

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!