工廠模式。何時使用工廠方法?什么時候在對象中使用工廠方法而不是Factory類是個好主意?
3 回答

MMMHUHU
TA貢獻1834條經驗 獲得超8個贊
如果你想在使用方面創建一個不同的對象。它是有益的。
public class factoryMethodPattern { static String planName = "COMMERCIALPLAN"; static int units = 3; public static void main(String args[]) { GetPlanFactory planFactory = new GetPlanFactory(); Plan p = planFactory.getPlan(planName); System.out.print("Bill amount for " + planName + " of " + units + " units is: "); p.getRate(); p.calculateBill(units); }}abstract class Plan { protected double rate; abstract void getRate(); public void calculateBill(int units) { System.out.println(units * rate); }}class DomesticPlan extends Plan { // @override public void getRate() { rate = 3.50; }}class CommercialPlan extends Plan { // @override public void getRate() { rate = 7.50; }}class InstitutionalPlan extends Plan { // @override public void getRate() { rate = 5.50; }}class GetPlanFactory { // use getPlan method to get object of type Plan public Plan getPlan(String planType) { if (planType == null) { return null; } if (planType.equalsIgnoreCase("DOMESTICPLAN")) { return new DomesticPlan(); } else if (planType.equalsIgnoreCase("COMMERCIALPLAN")) { return new CommercialPlan(); } else if (planType.equalsIgnoreCase("INSTITUTIONALPLAN")) { return new InstitutionalPlan(); } return null; }}
- 3 回答
- 0 關注
- 1044 瀏覽
添加回答
舉報
0/150
提交
取消