描述:封裝一基類,都繼承基類,當需要實例化不同對象時,可以通過一個工廠類實現。 實例:我通過一個計算器小程式來實現。 運算基類 /// <summary> /// 運算類 /// </summary> public class Operaction { private double _numberA
描述:封裝一基類,都繼承基類,當需要實例化不同對象時,可以通過一個工廠類實現。 實例:我通過一個計算器小程式來實現。 運算基類
/// <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(); } }
完了。