1. 程式人生 > >設計模式:單例模式(餓漢)

設計模式:單例模式(餓漢)

/**
 * 單例模式。
 * @author Bright Lee
 */
public class HungrySingleton {
	
	private static final HungrySingleton instance = 
			new HungrySingleton();
	
	private HungrySingleton() {
		System.out.println("構造方法被呼叫了,當前時間戳是:" + 
				System.currentTimeMillis());
	}
	
	public static HungrySingleton getInstance() {
		return instance;
	}

	public static void main(String[] args) {
		// 併發呼叫100遍,構造方法只會被呼叫一次:
		for (int i = 0; i < 100; i++) {
			new Thread() {
				public void run() {
					HungrySingleton.getInstance();
				}
			}.start();
		}
	}

}