设计模式|第一篇:简单工厂模式

1. 概念

简单工厂模式:创建对象工厂(用于生产对象),根据传入条件返回不同的对象

2.案例

本案例以计算器为例,主要实现逻辑有如下几步:

​1.根据用户传入的运算符,获取所需要的运算对象
2.根据获得的运算对像调用计算方法

  • 创建计算对象父类

    public interface Arithmetic {
    
      double calute(double arg1,double arg2);
    
    }
    
  • 创建各计算对象子类

    //加法
    public class Plus implements Arithmetic {
    
        @Override
        public double calute(double arg1, double arg2) {
            return arg1 + arg2;
        }
    }
    //减法
    public class Substruction implements Arithmetic {
    
      @Override
      public double calute(double arg1, double arg2) {
        return arg1 - arg2;
      }
    }
    //乘法
    public class Multiplication implements Arithmetic {
    
      @Override
      public double calute(double arg1, double arg2) {
        return arg1 * arg2;
      }
    }
    //除法
    public class Division implements Arithmetic {
    
      @Override
      public double calute(double arg1, double arg2) {
        if (0==arg2){
          throw new RuntimeException("除数不能为0");
        }
        return arg1 / arg2;
      }
    }
    
  • 创建计算对象工厂,根据条件返回不同的对象

    public class ArithmeticFactory {
    
      public static Arithmetic getArithmetic(String operator){
        switch (operator){
          case "+":
            return new Plus();
          case "-":
            return new Substruction();
          case "*":
            return new Multiplication();
          case "/":
            return new Division();
          default:
            throw new RuntimeException("输入运算符有误");
        }
      }
    }
    
  • 验证

    public class MainTest {
    
      public static void main(String[] args) {
        Arithmetic plus = ArithmeticFactory.getArithmetic("+");
        double calute = plus.calute(1, 2);
        System.out.println(calute);
    
        Arithmetic division = ArithmeticFactory.getArithmetic("/");
        calute = division.calute(1, 0);
        System.out.println(calute);
    
      }
    }
    
    
  • 案例结构

    为了方便理解,如下为本案例结构图:

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值