java单例模式

public class SingleInstance {
	private String name;
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	//【java 单例模式核心思想 begin】
	private SingleInstance() {}
	private static SingleInstance si = null;
	public static SingleInstance getInstance() {
		if(si == null) si = new SingleInstance();
		return si;
	}
	// 【java 单例模式核心思想 end】
	public void getInfo() {
		System.out.println("My name is " + name);
	}
	
	public static void main(String[] args) {
		SingleInstance si1 = SingleInstance.getInstance();
		si1.setName("bdzsl2013");
		System.out.println(si1.getName());
		SingleInstance si2 = SingleInstance.getInstance();
		si2.setName("2013bdzsl");
		System.out.println(si2.getName());
		si1.getInfo();
		si2.getInfo();
		if(si1 == si2) {
			System.out.println("same instance...");
		} else  if(si1 != si2) {
			System.out.println("different instance...");
		} else  {
			System.out.println("error!");
		}
	}
}

java单例模式_第1张图片



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