package pkg6.pkg38;
interface Fruit{
public void eat();
}
class Apple implements Fruit{
public void eat(){
System.out.println("**吃Apple");
}
}
class Orange implements Fruit{
public void eat(){
System.out.println("**吃Orange");
}
}
//工廠設計模式 Factory
class Factory {
public static Fruit getInstance(String className){
Fruit f = null;
if("apple".equals(className)){
f = new Apple();
}
if("orange".equals(className)){
f = new Orange();
}
return f;
}
}
public class Main {
public static void main(String[] args) {
// Fruit f = new Apple();
// f.eat();
// Fruit f2 = new Orange();
// f2.eat();
Fruit f =null;
//透過工廠取得我要的水果
//我要apple
f= Factory.getInstance("apple");
f.eat();
f= Factory.getInstance("orange");
f.eat();
}
}
執行結果:
**吃Apple
**吃Orange