简单工厂模式
- 通过封装、继承、多态把程序的耦合度降低。用设计模式使得程序更加的灵活,容易修改,并且易于复用。
- 让业务逻辑和界面逻辑分开,让它们耦合度降低,这样才容易维护和扩展。
csharp
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
//要求输入两个数和运算符号,得到结果
namespace Calculator
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("请输入一个数字");
string strNum1 = Console.ReadLine();
Console.WriteLine("请在输入一个数字");
string strNum2 = Console.ReadLine();
Console.WriteLine("请输入一个运算符");
string strOp = Console.ReadLine();
Operation oper = OperationFactory.CreateOperation(strOp);
double num1 = double.Parse(strNum1);
double num2 = double.Parse(strNum2);
double result = oper.GetResult(num1, num2);
Console.WriteLine($"{num1}{strOp}{num2}={result}");
}
}
public class Operation
{
private double _numberA = 0;
private double _numberB = 0;
public double NumberA
{
get
{
return _numberA;
}
set
{
_numberA = value;
}
}
public double NumberB
{
get
{
return _numberB;
}
set
{
_numberB = value;
}
}
public virtual double GetResult(double num1,double num2)
{
return 0;
}
}
class CalculateAdd : Operation
{
public override double GetResult(double num1, double num2)
{
return num1 + num2;
}
}
class CalculateSub : Operation
{
public override double GetResult(double num1, double num2)
{
return num1 - num2;
}
}
class CalculateMulti : Operation
{
public override double GetResult(double num1, double num2)
{
return num1 * num2;
}
}
class CalculateDiv : Operation
{
public override double GetResult(double num1, double num2)
{
try
{
return num1 / num2;
}
catch (Exception ex)
{
throw ex;
}
}
}
public class OperationFactory
{
static Operation oper = null;
public static Operation CreateOperation(string op)
{
switch (op)
{
case "+":
oper = new CalculateAdd();
break;
case "-":
oper = new CalculateSub();
break;
case "*":
oper = new CalculateMulti();
break;
case "/":
oper = new CalculateDiv();
break;
default:
break;
}
return oper;
}
}
}