- using System;
- using System.Collections.Generic;
- /**
- * 简单工厂模式
- */
- namespace StuDesignMode.SimpleFactory
- {
- abstract class AbsOperation
- {
- public double NumA { get; set; }
- public double NumB { get; set; }
- public virtual double GetResult()
- {
- return 0;
- }
- }
- /// <summary>
- /// 加法
- /// </summary>
- class OperationAdd:AbsOperation
- {
- public override double GetResult()
- {
- return this.NumA + this.NumB;
- }
- }
- /// <summary>
- /// 减法
- /// </summary>
- class OperationSub : AbsOperation
- {
- public override double GetResult()
- {
- return this.NumA - this.NumB;
- }
- }
- /// <summary>
- /// 乘法
- /// </summary>
- class OperationMul : AbsOperation
- {
- public override double GetResult()
- {
- return this.NumA * this.NumB;
- }
- }
- /// <summary>
- /// 除法
- /// </summary>
- class OperationDiv : AbsOperation
- {
- public override double GetResult()
- {
- double result = 0;
- if (this.NumB == 0)
- {
- throw new Exception("除数不能为0。");
- }
- result = this.NumA / this.NumB;
- return result;
- }
- }
- class OperationFactory
- {
- public static AbsOperation CreateOperate(string operate)
- {
- AbsOperation 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;
- }
- }
- //客户端测试
- class ClientTest
- {
- static void Main(string [] args)
- {
- AbsOperation oper = OperationFactory.CreateOperate("+");
- oper.NumA = 1;
- oper.NumB = 2;
- double result = oper.GetResult();
- Console.WriteLine(result);
- }
- }
- }
设计模式笔记(二)——简单工厂模式
最新推荐文章于 2024-04-02 18:35:26 发布