假設有個飲料店
public class BeverageShop{
Beverage beverage;
public Beverage orderBeverage(String type){
if(type.equals("紅茶")){
beverage = new BlackTea();
}else if(type.equals("奶茶")){
beverage = new MilkTea();
}
beverage.prepare();
beverage.box();
return beverage;
}
}
缺點:
1.未來要增加飲料種類, 要修改這class
2.prepare(),box()等等, 是固定不變的
Factory Pattern 的概念是怎麼把new一個object的處理封裝起來
現在把會變動的地方拉出來
public class SimpleBeverageFactry{優點:
public static Beverage createBeverage(String type){
if(type.equals("紅茶")){
beverage = new BlackTea();
}else if(type.equals("奶茶")){
beverage = new MilkTea();
}
return beverage;
}
}
public class BeverageShop{
SimpleBeverageFactry factory;
//這裡把使用的factory寫死了, 不好
public BeverageShop(SimpleBeverageFactry factory){
this.factory = factory;
}
public Beverage orderBeverage(String type){
Beverage beverage = factory.createBeverage(type);
beverage.prepare();
beverage.box();
return beverage;
}
}
1.把做飲料的步驟獨立出來, 未來只要有需要飲料的地方, 都可由這產生
上面是用一個factory來new object, 我們再來試試, 用extends
public atstract class BeverageShop{
public Beverage orderBeverage(String type){
Beverage beverage = createBeverage(type);
beverage.prepare();
beverage.box();
return beverage;
}
//現在new obejct的方式, 就由extends的類別自已實作
public abstract Beverage createBeverage(String type);
}
public class CocoBeverage extends Beverage{
public Beverage createBeverage(String type){
//做出coco獨特的飲料
}
}
public class QKBeverage extends Beverage{
public Beverage createBeverage(String type){
//做出qk caffee獨特的飲料
}
}
public class demo{
public static void main(String[] args){
BeverageShop coco = new CocoBeverage();
Beverage beverage = coco.orderBeverage();
xxx
}
}
寫到這裡, 我覺factory不可能這麼單純, 上面的例子應該很好懂, 跟一般在實作時的寫法類似
沒有留言:
張貼留言