`

Singleton单例模式

    博客分类:
  • J2SE
 
阅读更多
public class SingletonA 
{
	//私有属性
	private static int id = 1;
	
	//SingletonA的唯一实例
	private static SingletonA instance = new SingletonA();
	
	/*
	 * 将构造函数私有,防止外界构造SingletonA实例
	 */
	private SingletonA()
	{
		
	}
	
	/**
	 * 获取SingletonA的实例
	 * @return
	 */
	public static SingletonA getInstance()
	{
		return instance;
	}
	
	/**
	 * 获取实例的id,synchronized关键字表示该方法是线程同步的,即任一时刻最多只能
	 * 有一个线程进入该方法
	 * @return 返回id属性
	 */
	public synchronized int getId()
	{
		return id;
	}
	
	/**
	 * 将实例的id加1
	 */
	public synchronized void nextId()
	{
		id++;
	}
}

public class SingletonB 
{
	//私有属性
	private static int id = 1;
	//SingletonB的唯一实例
	private static SingletonB instance = null;
	
	/*
	 * 将构造函数私有,防止外界构造SingletonB实例
	 */
	private SingletonB()
	{
		
	}
	
	/**
	 * 获取SingletonB的唯一实例,使用synchronized关键字保证某一时刻只有
	 * 一个线程调用方法
	 * @return
	 */
	public static synchronized SingletonB getInstance()
	{
		//如果instance为空,便创建一个新的SingletonB实例,否则,返回已有的实例
		if(instance==null)
		{
			instance = new SingletonB();
		}
		return instance;
	}
	
	public synchronized int getId()
	{
		return id;
	}
	
	public synchronized void nextId()
	{
		id++;
	}
}

/**
 * 模式名称:单例模式
 * 模式特征:只能创建该类的一个实例
 * 模式用途:提供一个全局共享类实例
 */
public class SingletonTest 
{
	public static void main(String args[])
	{
		SingletonA a1 = SingletonA.getInstance();
		SingletonA a2 = SingletonA.getInstance();
		
		System.out.println("用SingletonA实现单例模式");
		System.out.println("调用nextId方法前:");
		System.out.println("a1.id=" + a1.getId());
		System.out.println("a2.id=" + a2.getId());
		a1.nextId();
		System.out.println("调用nextId方法后:");
		System.out.println("a1.id=" + a1.getId());
		System.out.println("a2.id=" + a2.getId());
		
		SingletonB b1 = SingletonB.getInstance();
		SingletonB b2 = SingletonB.getInstance();
		System.out.println("用SingletonB实现单例模式");
		System.out.println("调用nextId方法前:");
		System.out.println("b1.id=" + b1.getId());
		System.out.println("b2.id=" + b2.getId());
		b1.nextId();
		System.out.println("调用nextId方法后:");
		System.out.println("b1.id=" + b1.getId());
		System.out.println("b2.id=" + b2.getId());
	}
}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics