1. 程式人生 > >java 工廠模式 例項

java 工廠模式 例項

package 工廠模式;

public class FruitFactory {

	public static void main(String[] args) {
		Fruit apple=Factory.getInstance("apple");
		apple.eat();
		Fruit li=Factory.getInstance("Li");
		li.eat();
	}

}

interface Fruit {
	public void eat();
}

class Apple implements Fruit {

	@Override
	public void eat() {
		System.out.println("吃蘋果!");
	}

}

class Li implements Fruit {

	@Override
	public void eat() {
		System.out.println("吃梨子!");
	}

}

class Factory {// 定義工廠類
	public static Fruit getInstance(String className) {
		Fruit f = null;
		if ("apple".equals(className)) {
			f = new Apple();
		}
		if ("orange".equals(className)) {
			f = new Li();
		}
		return f;
	}
}