现在的位置: 首页 > 综合 > 正文

设计模式之单例模式

2013年04月18日 ⁄ 综合 ⁄ 共 1713字 ⁄ 字号 评论关闭

一、关于单例模式

顾名思义,单例模式即某个类我们希望它只有一个实例,比如AppWidgetManager类,它就只有一个实例,用户是不可能获得两个不同的实例的。

单例模式的类有什么特点呢?不同类的实例之间最大的不同在于它们的成员变量有差异,如果一个类只能有一个实例,那么它的成员变量就会特殊一些:

如果它具有对外可变(外部可以修改此值)的成员变量,那么这个成员变量一定是static的;

如果它是非静态的,那么它一定是private的,而且没有对外公开的可以设置此成员变量的方法。

其实,以上两点我觉得不是必须的,你可以违背以上两点去创建一个单例模式的类,只是你的类里的违背以上两点原则的成员变量或其修改方法其实是毫无意义的。

二、单例模式的实现(一)

如何设计单例模式的类呢?我们的主要任务是保证用户不能实例化该类,所以我们一定不能有public的构造方法,而且我们还必须至少有一个构造方法,否则用户就有可能调用默认的构造方法创建实例。同时,我们又必须为用户提供可以创建一个实例的方法,因此我们还必须有一个static方法用来获取实例。下面就是代码:

public class Singleton1 {
	
	/*
	 * This class must has a instance, a static instance.
	 * it is unique in each class.
	 * (about private ?)  
	 */
	private static Singleton1 singleton = null;
	
	/*
	 * Constructor method must be private (not public ?).
	 * There must be at least one constructor method, 
	 * or there will be default constructor method which can be called to get new instance.
	 */
	private Singleton1(){}
	
	/*
	 * This methord must be "public static" so that we can get a instance of Singleton
	 */
	public static Singleton1 getInstance(){
		if(singleton == null){
			singleton = new Singleton1();
		}
		
		return singleton;
	}
}

其实,上述代码存在一定问题:没有考虑并发的情况。当并发存在时,极有可能创建多个实例,这是我们不愿看到的。所以,我们需要考虑避免在并发时产生多个实例。

这里我还不知道如何写代码能够验证并发时产生多个实例????

三、单例模式的实现(二)

一种最简单的方法是:

public synchronized static Singleton2 getInstance()

但这也是最烂的方法,会造成许多无谓的等待。

package com.yutao.designmode;

public class Singleton2 {

	private static Singleton2 singleton = null;
	
	private Singleton2(){}
	
	public static Singleton2 getInstance(){
		
		if(singleton == null){
			synchronized(Singleton2.class){
				if(singleton == null){
					singleton = new Singleton2();
				}
			}
		}
		
		return singleton;
	}
}

四、单例模式的实现(三)

package com.yutao.designmode;

public class Singleton3 {

	private Singleton3(){}
	
	public static Singleton3 getInstance(){
		return SingletonInstance.singleton;
	}
	
	//this class must be private static
	private static class SingletonInstance{
		//this singleton must be static
		static Singleton3 singleton = new Singleton3();
	}
}

抱歉!评论已关闭.