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

感情迁移 提交于 2020-02-17 18:27:00

面向对象:封装、继承、多态,使得程序的耦合度降低,代码可以复用。

业务的封装:让业务逻辑与界面逻辑分开,耦合度降低。

简单的计算器程序

1)封装和继承

//定义一个Operation类
public class Operation
{
    //操作数
    private double NumberA {get;set;}
    private double NumberB {get;set;}
    
    private virtual double GetResult()
    {
         double result =0;
         return result;
     }      
}

//定义+、-、*、/操作方法
public class OperationAdd:Operation
{
     public override double GetResult()
     {
         double result =0;
         result = NumberA + NumberB;
         return result;
      }
}
public class OperationSub:Operation
{
     public override double GetResult()
     {
         double result =0;
         result = NumberA - NumberB;
         return result;
      }
}
public class OperationMul:Operation
{
     public override double GetResult()
     {
         double result =0;
         result = NumberA * NumberB;
         return result;
      }
}
public class OperationDiv:Operation
{
     public override double GetResult()
     {
         double result =0;
         if(NumberB == 0)
             throw new Exception("除数不能为0");
         result = NumberA / NumberB;
         return result;
      }
}
View Code

2)简单工厂类

public class OperationFactory
{
   public static Operation CreateOperation(string operate)
  { 
     Operation oper = null;
     switch(operate)
     {
          case "+":
              oper = new OperationAdd();
              break;
           case "-":
              oper = new OperationSub();
              break;
           case "*":
              oper = new OperationMul();
              break;
           case "/":
              oper = new OperationDiv();
              break;
      }
      return oper;
   }
  }
View Code

这样只需要输入运算符,工厂类就实例化合适的对象,通过多态返回父类的方式实现了计算器。

客户端代码:

Operation oper =null;
oper = OperationFactory.CreateOperation("+");
oper.NumberA=10;
oper.NumberB=15;
double result = oper.GetResult();
View Code

3)UML类图图示样例

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!