首页 > 代码库 > 单例模式之我见

单例模式之我见

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

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

	/**	 * 恶汉模式	 */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