简单工厂设计模式

以一个简单的计算器代码为例,来述说简单工厂设计模式。

运算类:

public class Operator_factory {
  Operator oper;
       public Operator operator(String oper){
      switch(oper){
      case "+": 
      this.oper = new AddOperator();
      break;
      case "-":
      this.oper = new SubOperator();
      break;
      case "*":
      this.oper = new MulOperator();
      break;
      case "/":
      this.oper = new DivOperator();
      break;
      }
      return this.oper;
       }
}

加减乘除类:

//加

public class AddOperator extends Operator{
       public double getResult(){
      double result = 0;
      result = getStrNumberA() + getStrNumberB();
      return result;
       }
}

//减

public class SubOperator extends Operator{
public double getResult(){
    double result = 0;
    result = getStrNumberA() - getStrNumberB();
    return result;
}
}

//乘

public class MulOperator extends Operator{
public double getResult(){
    double result = 0;
    result = getStrNumberA() * getStrNumberB();
    return result;
}
}

//除

public class DivOperator extends Operator{
public double getResult(){
  double result = 0;
  if(getStrNumberB() == 0) System.out.println("除数不能为0!");
  result = getStrNumberA() * getStrNumberB();
  return result;
}
}

//这些类继承了Operator类,实现多态性。方便代码维护和扩展。

工厂类

public class Operator_factory {
  Operator oper;
       public Operator operator(String oper){
      switch(oper){
      case "+": 
      this.oper = new AddOperator();
      break;
      case "-":
      this.oper = new SubOperator();
      break;
      case "*":
      this.oper = new MulOperator();
      break;
      case "/":
      this.oper = new DivOperator();
      break;
      }
      return this.oper;
       }
}

测试类

public class Test {

public static void main(String[] args) {

    Operator oper = new Operator_factory().operator("+");  //根据实际情况,调用工厂方法实例化各个类
    oper.setStrNumberA(1);
    oper.setStrNumberB(1);
    System.out.println(oper.getResult());
}

}

工厂设计模式的好处:一是解耦,二是方便代码的维护和扩展。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值