• 大话设计模式之简单工厂模式


    背景需求:

    模拟一个简单计算器。

    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 }

    总结:

    简单工厂模式适用于需要创建大量相同类型(父类相同或实现相同接口)实例的情景

  • 相关阅读:
    parted分区
    gitlab的还原
    hadoop2.7.3+spark2.0.1+scala2.11.8集群部署
    Daily record-September
    三次握手和四次挥手【转】
    “梅西式”程序员 【转】
    C++解析十-数据封装
    客户端、服务器代码实例
    网络整理
    C++解析九-数据抽象
  • 原文地址:https://www.cnblogs.com/xiaosiyuan/p/8999472.html
Copyright © 2020-2023  润新知