1.面向對象的3大屬性,封裝、繼承、多態,以一個加單的電腦為例: 創建一個父類Operation 有兩個屬性 和一個計算方法(虛方法),便於子類重寫: 1 public class Operation 2 { 3 private double _numberA = 0; 4 private dou ...
1.面向對象的3大屬性,封裝、繼承、多態,以一個加單的電腦為例:
創建一個父類Operation 有兩個屬性 和一個計算方法(虛方法),便於子類重寫:
1 public class Operation 2 { 3 private double _numberA = 0; 4 private double _numberB = 0; 5 6 public double NumberA 7 { 8 get { return _numberA; } 9 set { _numberA = value; } 10 } 11 12 public double NumberB 13 { 14 get { return _numberB; } 15 set { _numberB = value; } 16 } 17 18 /// <summary>虛方法 19 /// 20 /// </summary> 21 /// <returns></returns> 22 public virtual double GetResult() 23 { 24 double result = 0; 25 return result; 26 } 27 }View Code
接下來創建計算類,加減乘除類來集成操作類
加類
1 public class OperationAdd:Operation 2 { 3 public override double GetResult() 4 { 5 double result = 0; 6 result = NumberA + NumberB; 7 return result; 8 } 9 }View Code
減類
1 public class OperationSub:Operation 2 { 3 public override double GetResult() 4 { 5 double result = 0; 6 result = NumberA - NumberB; 7 return result; 8 } 9 }View Code
乘類
1 public class OperationMul:Operation 2 { 3 public override double GetResult() 4 { 5 double result = 0; 6 result = NumberA * NumberB; 7 return result; 8 } 9 }View Code
除類
1 public class OperationDiv:Operation 2 { 3 public override double GetResult() 4 { 5 double result = 0; 6 if (NumberB == 0) 7 throw new Exception("除數不能為0"); 8 result = NumberA / NumberB; 9 return result; 10 } 11 }View Code
然後通過簡單工廠類來創建計算的實例
1 public class OperationFactory 2 { 3 public static Operation createOperate(string operate) 4 { 5 Operation oper = null; 6 switch (operate) 7 { 8 case "+": 9 oper = new OperationAdd(); 10 break; 11 case "-": 12 oper = new OperationSub(); 13 break; 14 case "*": 15 oper = new OperationMul(); 16 break; 17 case "/": 18 oper = new OperationDiv(); 19 break; 20 } 21 return oper; 22 } 23 }View Code
最後通過界面去調用:
1 static void Main(string[] args) 2 { 3 Operation oper; 4 oper = OperationFactory.createOperate("+"); 5 oper.NumberA = 1; 6 oper.NumberB = 2; 7 double result = oper.GetResult(); 8 Console.WriteLine(result); 9 Console.ReadKey(); 10 }View Code
這裡把計算過程都封裝成一個方法,每個計算類又集成了操作類,這樣由於每個方法都重寫了計算方法,這裡表現出一個方法的不同表現形態,如果以後要增加其他的方法,只需要繼承操作類 重寫計算方法即可,這樣也不會對原有的程式進行修改,實現瞭解耦,面向對象語言的優點在於可維護性,可復用,可擴展、靈活性。
以上為自學的一點總結,希望有不對的地方,請大家指點,謝謝