`

设计模式之单例模式

阅读更多
java设计模式之单例模式


一、单例模式的介绍
     Singleton是一种创建型模式,指某个类采用Singleton模式,则在这个类被创建后,只可能产生一个实例供外部访问,并且提供一个全局的访问点

二、单例模式的实现

实现的方式有如下几种:
/**
 * 
 * 单例模式的实现:饿汉式,线程安全 但效率比较低
 */
public class SingletonTest {

	private SingletonTest() {
	}

	private static final SingletonTest instance = new SingletonTest();

	public static SingletonTest getInstancei() {
		return instance;
	}

}


/**
 * 单例模式的实现:饱汉式,非线程安全 
 * 
 */
public class SingletonTest {
	private SingletonTest() {
	}

	private static SingletonTest instance;

	public static SingletonTest getInstance() {
		if (instance == null)
			instance = new SingletonTest();
		return instance;
	}
}


/**
 * 线程安全,但是效率非常低
 * @author vanceinfo
 *
 */
public class SingletonTest {
	private SingletonTest() {
	}

	private static SingletonTest instance;

	public static synchronized SingletonTest getInstance() {
		if (instance == null)
			instance = new SingletonTest();
		return instance;
	}
}


/**
 * 线程安全  并且效率高
 *
 */
public class SingletonTest {
	private static SingletonTest instance;

	private SingletonTest() {
	}

	public static SingletonTest getIstance() {
		if (instance == null) {
			synchronized (SingletonTest.class) {
				if (instance == null) {
					instance = new SingletonTest();
				}
			}
		}
		return instance;
	}
}




/**
 * 静态内部类的方式实现的单列
 */
public class SingletonTest {

  public static class Singleton {
    public static SingletonTest instance = new SingletonTest();
  }

  public static SingletonTest getInstance() {
    return Singleton.instance;
  }
}



/**
 * 枚举类型实现的单列
 */
public enum SingletonTest {
  INSTANCE;

  public static SingletonTest getInstance() {
    return INSTANCE;
  }
}


分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics