2017年2月1日 星期三

C# Template Pattern 樣板模式


遇到流程一樣,但是處理邏輯不一樣的狀況,可利用 Template Pattern 樣板模式

建立一個 UnitFlowBase 抽像類別提供框架,裡面有三個方法
Node1      (每個測試類別只都執行一次)
Node2      (每次執行測試方法時都執行一次)
....
UnitTest   (執行測試方法,裡面通常會執行多個 UnitFlowBase  提供的方法
所以才會說 UnitFlowBase 提供框架,例如:此範例  UnitTest 執行了 Node2() 與 Node3())

  1. public abstract class UnitFlowBase
  2. {
  3. protected UnitFlowBase()
  4. {
  5. Node1();
  6. }
  7. protected virtual void Node1()
  8. {
  9. }
  10. protected virtual void Node2()
  11. {
  12. }
  13. protected abstract bool Node3();
  14. public void UnitTest()
  15. {
  16. Node2();
  17. Console.WriteLine(Node3() ? "Assert Successful." : "Assert Fail.");
  18. }
  19. }

建立 UnitCounter1 與 UnitCounter2
Execute方法 顯示目前 ClassCount 跟 MethodCount 執行次數

  1. public class UnitCounter1 : UnitFlowBase
  2. {
  3. private int _classCounter = 0;
  4. private int _methodCounter = 0;
  5. protected override void Node1()
  6. {
  7. _classCounter++;
  8. }
  9. protected override void Node2()
  10. {
  11. _methodCounter++;
  12. }
  13. protected override bool Node3()
  14. {
  15. Console.WriteLine($"ClassCounter1 : {_classCounter}");
  16. Console.WriteLine($"MethodCounter1: { _methodCounter}");
  17. return true;
  18. }
  19. }
  20. public class UnitCounter2 : UnitFlowBase
  21. {
  22. private int _classCounter = 0;
  23. private int _methodCounter = 0;
  24. protected override void Node1()
  25. {
  26. _classCounter += 2;
  27. }
  28. protected override void Node2()
  29. {
  30. _methodCounter += 2;
  31. }
  32. protected override bool Node3()
  33. {
  34. Console.WriteLine($"ClassCounter2 : {_classCounter}");
  35. Console.WriteLine($"MethodCounter2: { _methodCounter}");
  36. return true;
  37. }
  38. }

建立一個 UnitCounter1 與 UnitCounter2 類別,各執行二次 UnitTest 方法

  1. class Program
  2. {
  3. static void Main(string[] args)
  4. {
  5. UnitCounter1 unit1_ = new UnitCounter1();
  6. UnitCounter2 unit2_ = new UnitCounter2();
  7. unit1_.UnitTest();
  8. unit1_.UnitTest();
  9. unit2_.UnitTest();
  10. unit2_.UnitTest();
  11. }
  12. }

執行結果:
ClassCount : 1
MethodCount : 1
Assert Successfull.
ClassCount : 1
MethodCount : 2
Assert Successfull.
ClassCount : 2
MethodCount : 2
Assert Successfull.
ClassCount : 2
MethodCount : 4
Assert Successfull.



















Visual Studio 2017/2019 推薦的擴充功能與更新

參考文章: 覺得 Google 的 Blogger 不太順手?透過 HTML 的 iframe 移花接木 HackMD