描述:封装一基类,都继承基类,当需要实例化不同对象时,可以通过一个工厂类实现。
实例:通过一个计算器小程序来实现。
代码实现如下:
运算基类
/// <summary> /// 运算类 /// </summary> public class Operaction { 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; } }
运算子类,我统一放在OperactionAll.cs中了
/// <summary> /// 加 /// </summary> class OperactionAdd : Operaction { /// <summary> /// 运算方法 /// </summary> /// <returns></returns> public override double GetResult() { double result = 0; result = NumberA + NumberB; return result; } } /// <summary> /// 减 /// </summary> class OperactionSub : Operaction { public override double GetResult() { double result = 0; result = NumberA - NumberB; return result; } } /// <summary> /// 乘 /// </summary> class OperactionMul : Operaction { public override double GetResult() { double result = 0; result = NumberA * NumberB; return result; } } /// <summary> /// 除 /// </summary> class OperactionDiv : Operaction { public override double GetResult() { double result = 0; result = NumberA / NumberB; return result; } }
工厂类
/// <summary> /// 工厂类 /// </summary> public class OperactionFactory { //创建实例的方法 public static Operaction CreateOperaction(string Operacte) { Operaction oper = null; switch (Operacte) { case "+": oper = new OperactionAdd(); break; case "-": oper = new OperactionSub(); break; case "*": oper = new OperactionMul(); break; case "/": oper = new OperactionDiv(); break; } return oper; } }
客户端调用
/// <summary> /// 客户端调用 /// </summary> class Program { static void Main(string[] args) { Operaction oper = null; oper = OperactionFactory.CreateOperaction("-"); //通过工厂创建实体 oper.NumberA = 10; oper.NumberB = 5; double result = oper.GetResult();//运算方法 Console.WriteLine(result); Console.ReadLine(); } }
完了。代码:点击下载
时间: 2024-10-20 13:32:34