大话设计模式_单例模式

一:单线程

package com.wzs.design;

/**
 * 大话设计模式--page214 单例模式
 * 
 * @author Administrator
 * 
 */
public class Singleton {
	private static Singleton instance;

	public static Singleton getInstance() {
		if (null == instance) {
			instance = new Singleton();
		}
		return instance;
	}

	public static void main(String[] args) {
		Singleton singleton1 = Singleton.getInstance();
		Singleton singleton2 = Singleton.getInstance();
		if (singleton1 == singleton2) {
			System.out.println("两个对象是同一个实例.");
		}
	}
}


二:多线程

package com.wzs.three;

/**
 * 大话设计模式--page214 单例模式(多线程中,双重锁定)
 * 
 * @author Administrator
 * 
 */
public class Singleton {
	private static Singleton instance;
	private static String lock = "lock";

	public static Singleton getInstance() {
		if (null == instance) {
			synchronized (lock) {
				if (null == instance) {
					instance = new Singleton();
				}
			}
		}
		return instance;
	}

	public static void main(String[] args) {
		Singleton singleton1 = Singleton.getInstance();
		Singleton singleton2 = Singleton.getInstance();
		if (singleton1 == singleton2) {
			System.out.println("两个对象是同一个实例.");
		}
	}
}


你可能感兴趣的:(多线程,单例模式,大话设计模式)