定义:
由一个工厂对象决定创建出哪一种产品类的实例。工厂类内部有必要的判断逻辑可以决定什么时候创建哪一种产品的实例。
这里以大话设计模式中的计算器为例子。
一个计算器Operation 抽象类, 然后定义了Add, Substract, Multiply, Divide 类来继承它。
另有 输入一个 String, 返回想要的具体类。
1 package com.disignpattern.simplefactory; 2 3 public abstract class Operation { 4 private double a; 5 private double b; 6 public double getA() { 7 return a; 8 } 9 public void setA(double a) { 10 this.a = a; 11 } 12 public double getB() { 13 return b; 14 } 15 public void setB(double b) { 16 this.b = b; 17 } 18 19 public abstract double getResult(); 20 21 } 22 23 24 25 public class OperationAdd extends Operation { 26 @Override 27 public double getResult() { 28 return getA() + getB(); 29 } 30 } 31 32 public class OperationDiv extends Operation { 33 @Override 34 public double getResult() { 35 36 return getA() / getB(); 37 } 38 } 39 40 public class OperationMul extends Operation { 41 @Override 42 public double getResult() { 43 return getA() * getB(); 44 } 45 } 46 47 48 public class OperationSub extends Operation { 49 @Override 50 public double getResult() { 51 return getA() - getB(); 52 } 53 }
最后上工厂方法。
1 public class OperationFactory { 2 public static Operation getOperation(String s) { 3 Operation operation = null; 4 switch (s) { 5 case "+": 6 operation = new OperationAdd(); 7 break; 8 case "-": 9 operation = new OperationSub(); 10 break; 11 case "*": 12 operation = new OperationMul(); 13 break; 14 case"/": 15 operation = new OperationDiv(); 16 break; 17 } 18 19 return operation; 20 } 21 }
jdk源码使用简单工厂方法的案例分析
一般要用到Switch case.
1 private static Calendar createCalendar(TimeZone zone, 2 Locale aLocale) 3 { 4 CalendarProvider provider = 5 LocaleProviderAdapter.getAdapter(CalendarProvider.class, aLocale) 6 .getCalendarProvider(); 7 if (provider != null) { 8 try { 9 return provider.getInstance(zone, aLocale); 10 } catch (IllegalArgumentException iae) { 11 // fall back to the default instantiation 12 } 13 } 14 15 Calendar cal = null; 16 17 if (aLocale.hasExtensions()) { 18 String caltype = aLocale.getUnicodeLocaleType("ca"); 19 if (caltype != null) { 20 switch (caltype) { 21 case "buddhist": 22 cal = new BuddhistCalendar(zone, aLocale); 23 break; 24 case "japanese": 25 cal = new JapaneseImperialCalendar(zone, aLocale); 26 break; 27 case "gregory": 28 cal = new GregorianCalendar(zone, aLocale); 29 break; 30 } 31 } 32 } 33 }
原文:https://www.cnblogs.com/tangdatou/p/11474336.html