# 设计模式学习（一）：简单工厂模式练习

Operation.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DesignPatterns
{

/// <summary>
/// 运算类
/// </summary>
public class Operation
{
protected string Sign = "";
private double fNumberA = 0, fNumberB = 0;

public double NumberA
{
get { return fNumberA;}
set { fNumberA = value; }
}

public double NumberB
{
get { return fNumberB; }
set { fNumberB = value; }
}

public virtual double Result
{
get { return 0; }
}

public string ToString()
{
return Convert.ToString(NumberA) + Sign +
Convert.ToString(NumberB) + "=" + Convert.ToString(Result);
}
}

/// <summary>
/// 加法运算类
/// </summary>
class OperationAdd : Operation
{
{
Sign = "+";
}

public override double Result
{
get { return (NumberA + NumberB); }
}
}

/// <summary>
/// 减法运算类
/// </summary>
class OperationSub : Operation
{
public OperationSub()
{
Sign = "-";
}

public override double Result
{
get { return (NumberA - NumberB); }
}
}

/// <summary>
/// 乘法运算类
/// </summary>
class OperationMul : Operation
{
public OperationMul()
{
Sign = "*";
}

public override double Result
{
get { return NumberA * NumberB; }
}
}

/// <summary>
/// 除法运算类
/// </summary>
class OperationDiv : Operation
{
public OperationDiv()
{
Sign = "/";
}

public override double Result
{
get
{
if(NumberB==0) {
throw new Exception("被除数为零");
}
return (NumberA / NumberB);
}
}
}

/// <summary>
/// 简单工厂类
/// </summary>
public class OperationFactory
{
/// <summary>
/// 根据运算符取对应的运算类
/// </summary>
/// <param name="strOperation">运算符</param>
/// <returns>运算类</returns>
public static Operation GetOperation(string strOperation)
{
Operation fOperation = null;
switch (strOperation)
{
case "+":
fOperation = new OperationAdd();
break;
case "-":
fOperation = new OperationSub();
break;
case "*":
fOperation = new OperationMul();
break;
case "/":
fOperation = new OperationDiv();
break;
}
return fOperation;
}
}
}


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DesignPatterns
{
class Program
{
static void Main(string[] args)
{
Operation op = OperationFactory.GetOperation("*");
op.NumberA = 123.22;
op.NumberB = 111;
Console.Out.WriteLine(op.ToString());

}
}
}

UML图

• 0
点赞
• 0
收藏
觉得还不错? 一键收藏
• 0
评论
12-20
05-06 1371
05-01 266
01-18 1万+
08-28 256
03-28
10-10
04-05
06-30 4047
05-20 482

### “相关推荐”对你有帮助么？

• 非常没帮助
• 没帮助
• 一般
• 有帮助
• 非常有帮助

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