设计模式之简单工厂模式

需求:现在不知道实例化的对象,也不知道将来会不会需要增加实例化的对象时,需要一个类单独管理实例化的过程。
解决方案:运用简单工厂设计模式,创建一个新类来进行对对象实例化的管理。这个新类就是工厂。
例:创建一个运算器程序
1.创建计算父类

   public class Operation{
         public double a=0.0;
         public double b=0.0;
         public double getResult(){
               double result=0.0;
               return result; 
         }
   }
      2.创建具体运算类
  public class AddOperation extends Operation{
         public double getResult(){
                  double result=0;
                  result=a+b;
                  return result; 
         }
  }
  public class SubOperation extends Operation{
         public double getResult(){
                  double result=0;
                  result=a-b;
                  return result; 
         }
  }
  public class MulOperation extends Operation{
         public double getResult(){
                  double result=0;
                  result=a*b;
                  return result; 
         }
  }
  public class DivOperation extends Operation{
         public double getResult(){
                  if(b==0){
                       throw new Exception("除数不可以为0");
                  }
                  double result=0;
                  result=a/b;
                  return result; 
         }
  }
  3.创建简单工厂
  public class OperationFactory{
           public static Operation createOperate(string operate){
                    Operation oper=null;
                    switch(operate){
                             case:"+":
                                   oper=new AddOperation();
                                   break;
                            case:"-":
                                   oper=new SubOperation();
                                   break;
                           case:"*":
                                   oper=new MulOperation();
                                   break;
                           case:"/":
                                   oper=new DivOperation();
                                   break;
                    }
                    return oper;
           }          
  }
  4.客户端代码
  Operation oper;
  oper=OperationFactory.createOperate("+");
  oper.a=1;
  oper.b=2;
  double result=oper.getResult;

优点:将来需要拓展运算符号以及运算算法时,客户端可以不予改变,只需要增加相应的运算类以及去工厂内增加相应的判断即可。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值