Factory Pattern
現在假設我的飲料店有很多家了, 但台北與高雄不同的店, 需要的原料會不同
所以若有個原料產生的工廠呢?
public interface SourceFactory{
public Sugar createSugar();
public Ice createIce();
}
public class TaipeiSourceFactory implements SourceFactory{
public Sugar createSugar(){
return new Sugar();
}
public Ice createIce(){
return new Ice();
}
}
public class KaoshungSourceFactory implements SourceFactory{
//自訂高雄的工廠要怎麼生產原料 xxx
}
public abstract class Beverage{
Sugar sugar;
Ice ice;
abstract void prepare();
public void box(){
//把飲料裝箱
}
}
public class MikeTeaBeverage extends Beverage{ //做奶茶
TaipeiSourceFactory taipeiSourceFactory ;
public MikeTeaBeverage(TaipeiSourceFactory taipeiSourceFactory ){
this.taipeiSourceFactory = taipeiSourceFactory ;}
void prepare(){Sugar sugar = taipeiSourceFactory.createSugar();
Ice ice = taipeiSourceFactory.createIce();}
}public class BlackTeaBeverage extends Beverage{
//相同 xxx
}
我覺上面的寫法, 跟使用utils的想法類似, 把會重複利用的拉出來
最後, 上一篇的BeverageShop, 我們來extends它, 就可以很容易的擴充了
public class CocoBeverageShop extends BeverageShop{
public Beverage createBeverage(String type){
Beverage beverage;
SourceFactory factory = new TaipeiSourceFactory(); //我coco的店要用台北的原料
if(type.equals(「紅茶")){
...
}else if(type.equals(「奶茶")){
beverage = new MikeTeaBeverage(factory);
}
return beverage;
}
}
要依賴抽象, 不要依賴實作的類 --> 不是我講的
會變動的東西, 就把它變成抽象,再去實作, 這樣物件之間的關係就可以分開
2 意見:
寫的不錯唷.
感恩啊~XD
張貼留言