用简单工厂模式实现加减乘除运算等计算

本文参考《大话设计模式》进行总结

初级版本:

class program
{
	statis void Main(String[] args)
	{
		try
		{
			Console.Write("请输入数字A: ");
			string strNumberA = Console.ReadLine();
			Console.Write("请选择符号(+、-、*、/): ");
			string strOperate = Console.ReadLine();
			Console.Write("请输入数字B: ");
			string strNumberB = Console.ReadLine();
			sreing strResult = "";
			switch (strOperate)
			{
				case "+":
					strResult = Convert.ToString(Convert.ToDouble(strNumberA) + Convert.ToDouble(strNumberB));
					break;
				case "-":
					strResult = Convert.ToString(Convert.ToDouble(strNumberA) - Convert.ToDouble(strNumberB));
					break;
				case "*":
					strResult = Convert.ToString(Convert.ToDouble(strNumberA) * Convert.ToDouble(strNumberB));
					break;
				case "/":
					if (strNumberB != "0")
						strResult = Convert.ToString(Convert.ToDouble(strNumberA) / Convert.ToDouble(strNumberB));
					else
						strResult = "除数不能为0";
					break;
			}
			Console.WriteLine("结果是: " + strResult);
			Console.ReadLine();
		}
		catch (Exception ex)
		{
			Console.WriteLine("您的输入有错: " + ex.Message);
		}
	}
}

简单工厂模式实现方法:

Operation运算类(父类):

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 result = 0;
		return result;
	}
}

加减乘除类:

class OperationAdd : Operation
{
	public override double GetResult()
	{
		double result = 0;
		result = NumberA + NumberB;
		return result;
	}
}
class OperationSub : Operation
{
	public override double GetResult()
	{
		double result = 0;
		result = NumberA - NumberB;
		return result;
	}
}
class OperationMul : Operation
{
	public override double GetResult()
	{
		double result = 0;
		result = NumberA * NumberB;
		return result;
	}
}
class OperationDiv : Operation
{
	public override double GetResult()
	{
		double result = 0;
		if (NumberB == 0)
			throw new Exception("除数不能为0。");
		result = NumberA / NumberB;
		return result;
	}
}

简单运算工厂类:

public class OperationFactory
{
	public static Operation createOperate(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;
	}
}

客户端代码:

Operation oper;
oper = OperationFactory.createOperate(“+”);
oper.NumberA = 1;
oper.NumberB = 2;
double result = oper.GetResult();

简单来说就是创建一个单独的工厂类专门实例化出合适的对象,当然加减乘除类也采用了松耦合,通过多态,返回父类的方式实现了计算器的结果。具备可扩展性。

 

 

 

 

 

你可能感兴趣的:(设计模式)