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

单例模式之我见

时间:2014-07-13 23:32:38      阅读:262      评论:0      收藏:0      [点我收藏+]

标签:style   blog   java   color   for   div   

单例模式是一种最常见的设计模式,校招中如果要进大公司,必须透彻的掌握单例模式,总结了常见的一些单例模式

首先是最简单的恶汉模式,恶汉模式是一种最简单的单例模式

	/**
	 * 恶汉模式
	 */
public class SingleTon {
	private static final SingleTon instance = new SingleTon();
	private SingleTon(){
		
	}
	public static SingleTon getInstance() {
		return instance;
	}
}

  其实是懒汉加载模式,最简单的懒汉加载模式如下

public class SingleTon {
	private static SingleTon instance = null ;
	private SingleTon(){
		
	}
	public  static SingleTon getInstance() {
		if (instance == null) {
			instance = new SingleTon();
		}
		return instance;
	}
}

但上述懒汉模式是线程不安全的,可以对其进行加锁

public class SingleTon {
	private static SingleTon instance = null ;
	private SingleTon(){
		
	}
	public static synchronized SingleTon getInstace(){
		if (instances == null ) {
			return instances = new SingleTon();
		}
		return instances;
	}
}

  或者双重加锁模式

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

  

单例模式还可以用内部类来实现

      
public class SingleTon {
      public static class SingleTonHolder{
		private static SingleTon instance = new SingleTon();
	}

	public SingleTon() {
	}
	public static SingleTon getInstance() {
		return SingleTonHolder.instance;
	}
}    

看看大牛Jon Skeet是怎么写单例的 (c#版)

public sealed class Singleton
{
    Singleton()
    {
    }

    public static Singleton Instance
    {
        get
        {
            return Nested.instance;
        }
    }

    class Nested
    {
        // Explicit static constructor to tell C# compiler
        // not to mark type as beforefieldinit
        static Nested()
        {
        }

        internal static readonly Singleton instance = new Singleton();
    }
}
有任何疑问可联系本人huwei08@baidu.com

单例模式之我见,布布扣,bubuko.com

单例模式之我见

标签:style   blog   java   color   for   div   

原文地址:http://www.cnblogs.com/huwei0814/p/3840387.html

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