Java设计模式之“单例”

  • 介绍
单例模式是相对比较常见的一种设计模式。其本质就是使一个类对象,在同一个JVM中只有一个实例。这种设计模式经常会和工厂模式配合使用。
  • 示例
下面是一个没有考虑线程安全的例子
[codesyntax lang="java" lines="normal"]
package org.suren.pattern;


/**
 * @author suren
 * @date 2015-4-1
 *
 * 一个最简单、直接的单例实现例子。
 * 没有考虑线程安全问题,所以在运行3到5次就能看到打印出来的对象不止一个。
 *
 * http://surenpi.com
 */
public class SingleTest
{

	/**
	 * @param args
	 */
	public static void main(String[] args)
	{
		int count = 10;

		for(int i = 0; i < count; i++)
		{
			new Thread(){
				public void run()
				{
					System.out.println(Single.getInstance());
				}
			}.start();
		}

		for(int i = 0; i < count; i++)
		{
			new Thread(){
				public void run()
				{
					System.out.println(Single.getInstance());
				}
			}.start();
		}
	}
}

/**
 * @author suren
 * @date 2015-4-1
 *
 * http://surenpi.com
 */
class Single
{
	private static Single single = null;

	//私有化默认构造器,这样就保证了无法从类的外部调用构造方法
	private Single(){}

	/**
	 * 提供静态方法获取实例对象
	 * @return
	 */
	public static Single getInstance()
	{
		if(single == null)
		{
			single = new Single();
		}

		return single;
	}
}
[/codesyntax]
下面是线程安全的例子
[codesyntax lang="java" lines="normal"]
package org.suren.pattern.safe1;


/**
 * @author suren
 * @date 2015-4-1
 *
 * 一个最简单、直接的单例实现例子。
 * 没有考虑线程安全问题,所以在运行3到5次就能看到打印出来的对象不止一个。
 *
 * http://surenpi.com
 */
public class SafeSingleTest
{

	/**
	 * @param args
	 */
	public static void main(String[] args)
	{
		int count = 5000;
		final long begin = System.currentTimeMillis();

		for(int i = 0; i < count; i++)
		{
			new Thread(){
				public void run()
				{
					System.out.println(Single.getInstance());
					System.out.println(System.currentTimeMillis() - begin);
				}
			}.start();
		}

		for(int i = 0; i < count; i++)
		{
			new Thread(){
				public void run()
				{
					System.out.println(Single.getInstance());
					System.out.println(System.currentTimeMillis() - begin);
				}
			}.start();
		}
	}
}

/**
 * @author suren
 * @date 2015-4-1
 *
 * http://surenpi.com
 */
class Single
{
	private static Single single = null;

	//私有化默认构造器,这样就保证了无法从类的外部调用构造方法
	private Single(){}

	/**
	 * 提供静态方法获取实例对象
	 * @return
	 */
	public static synchronized Single getInstance()
	{
		if(single == null)
		{
			single = new Single();
		}

		return single;
	}
}
[/codesyntax]
  • 参考

你可能感兴趣的:(java,单例,设计模式)