工厂模式。何时使用工厂方法?什么时候在对象中使用工厂方法而不是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 关注
- 981 浏览
添加回答
举报
0/150
提交
取消