背景需求:
模拟一个简单计算器。
UML类图:
说明:
抽象类AbstractOperation有一个抽象方法getResult和两个成员变量,加减乘除分别继承AbstractOperation并实现getResult方法即可。OperationFactory是一个简单工厂方法,可根据入参实例化不同的子类。
demo:
AbstractOperation类:
1 public abstract class AbstractOperation { 2 3 private Double firstNumber; 4 private Double secondNumber; 5 6 public abstract Double getResult() throws Exception; 7 8 public Double getFirstNumber() { 9 return firstNumber; 10 } 11 12 public void setFirstNumber(Double firstNumber) { 13 this.firstNumber = firstNumber; 14 } 15 16 public Double getSecondNumber() { 17 return secondNumber; 18 } 19 20 public void setSecondNumber(Double secondNumber) { 21 this.secondNumber = secondNumber; 22 } 23 }
加法类OperationAdd:
1 public class OperationAdd extends AbstractOperation { 2 @Override 3 public Double getResult() { 4 return getFirstNumber() + getSecondNumber(); 5 } 6 }
减法类OperationSub:
1 public class OperationSub extends AbstractOperation { 2 @Override 3 public Double getResult() { 4 return getFirstNumber() - getSecondNumber(); 5 } 6 }
简单工厂类OperationFactory:
1 public class OperationFactory { 2 3 public static AbstractOperation createOperation(String operate){ 4 AbstractOperation operation = null; 5 6 switch (operate){ 7 case "+":operation = new OperationAdd();break; 8 case "-":operation = new OperationSub();break; 9 default:break; 10 } 11 return operation; 12 } 13 }
客户端测试类:
1 public class Main { 2 3 public static void main(String[] args) throws Exception { 4 5 AbstractOperation operation = 6 OperationFactory.createOperation("+"); 7 operation.setFirstNumber(10d); 8 operation.setSecondNumber(20d); 9 System.out.println(operation.getResult()); 10 11 } 12 }
总结:
简单工厂模式适用于需要创建大量相同类型(父类相同或实现相同接口)实例的情景