1. 程式人生 > >java筆試--設計模式

java筆試--設計模式

單列模式

public class Singleton {
	/*
	 * private static Singleton instance; private Singleton(){
	 * 
	 * } public static Singleton getInstance(){ if(instance==null){ synchronized
	 * (Singleton.class) { if(instance==null){ instance=new Singleton(); } } }
	 * return instance; }
	 */

	private static Singleton instance;

	private Singleton() {

	}

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


工廠模式

interface Animal {
	public void say();

}

class Cat implements Animal {
	public void say() {
		System.out.print("貓說話");
	}
}

class Mouse implements Animal {
	public void say() {
		System.out.print("老鼠說話");
	}
}

class Factory {
	public static Animal getInstance(String className) {
		Animal animal = null;
		if ("Cat".equals(className)) {
			animal = new Cat();
		}
		if ("Mouse".equals(className)) {
			animal = new Mouse();
		}
		return animal;
	}
}