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

[设计模式] 单例设计模式

时间:2014-09-14 21:56:17      阅读:167      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   div   sp   log   on   c   new   

1.懒汉式(内部类式)

  

/**
 * Created by pmx on 14-9-14.
 */
public class Singleton {
private Singleton() {} public static Singleton getInstance() { return SingletonHolder.instance; } static class SingletonHolder { private static Singleton instance = new Singleton(); } }

 

2.懒汉式(同步)

/**
 * Created by pmx on 14-9-14.
 */
public class Singleton {

    private static Singleton singleton = null;

    private Singleton() {}


    public static Singleton getInstance() {

        if (singleton == null)
        {
            synchronized (Singleton.class)
            {
                if (singleton == null)
                    singleton = new Singleton();
            }
        }
        return singleton;
    }


}

 

[设计模式] 单例设计模式

标签:style   blog   color   div   sp   log   on   c   new   

原文地址:http://www.cnblogs.com/tiny1990/p/3971550.html

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