`
Scliu123
  • 浏览: 39996 次
  • 性别: Icon_minigender_1
  • 来自: 杭州
最近访客 更多访客>>
社区版块
存档分类
最新评论

JDK_实例(Singleton单列模式)

阅读更多

A

package book.oo.singleton;

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

}

 

 

B

package book.oo.singleton;

public class SingletonB {
	//私有属性
	private static int id = 1;
	//SingletonB的唯一实例
	private static SingletonB instance = null;
	
	//将构造函数私有,防止外界构造SingletonB实例
	private SingletonB() {
	}
	//获取SingletonB的唯一实例,同样用synchronized关键字保证某一时刻只有一个线程调用此方法。
	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++;
	}
}

 

 

测试

package book.oo.singleton;

/*
 * 模式名称:单建模式
 * 模式特征:只能创建该类的一个实例
 * 模式用途:提供一个全局共享类实例
 **/
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());
		//SingletonA和SingletonB的区别:前者是在类被加载的时候就创建了实例,
		//而后者是在调用getInstance方法时才创建实例。
		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