DesignPattern_Java:SingletonPattern

单例模式 SingletonPattern

Ensure a class has only one instance,and provide a global point of access to it.

单例模式的主要作用是确保一个类只有一个实例存在。

懒汉式单例类:第一次引用类时,才进行对象实例化。


package com.DesignPattern.Creational.Singleton;

public class Singleton_lHan {

	private static Singleton_lHan _instance = null;

	private Singleton_lHan() {
	}

	synchronized public static Singleton_lHan getInstance() {
		if (_instance == null) {
			_instance = new Singleton_lHan();
		}
		return _instance;
	}
}


饿汉式单例类:类加载时,就进行对象实例化。

package com.DesignPattern.Creational.Singleton;

public class Singleton_eHan {

	private static Singleton_eHan m_instance = new Singleton_eHan();

	private Singleton_eHan() {
	}

	public static Singleton_eHan getInstance() {
		return m_instance;
	}
}

单例模式的实例

创建一个饿汉式单例类:GlobalNum.java

package com.DesignPattern.Creational.Singleton;

public class GlobalNum {

	private static GlobalNum gn = new GlobalNum();
	private int num = 0;

	public static GlobalNum getInstance() {
		return gn;
	}

	public synchronized int getNum() {
		return ++num;
	}
}

SingleDemo.java

package com.DesignPattern.Creational.Singleton;

public class SingleDemo {

	//测试单例模式
	public static void main(String[] args) {
		//创建线程A
		NumThread threadA = new NumThread("thread A");
		//创建线程B
		NumThread threadB = new NumThread("thread B");
		//启动线程
		threadA.start();
		threadB.start();

	}
}
//线程类
class NumThread extends Thread {

	private String threadName;

	public NumThread(String name) {
		threadName = name;
	}

	//重写线程的run方法(线程任务)
	public void run() {
		GlobalNum gnObj = GlobalNum.getInstance();
		//循环访问,输出访问次数
		for (int i = 0; i < 5; i++) {
			System.out.println(threadName + "第" + gnObj.getNum() + "次访问!");
			try {
				this.sleep(1000);	//线程休眠1000毫秒
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}

}


posted on 2015-08-20 21:28  _noname  阅读(176)  评论(0编辑  收藏  举报