剛剛在書上發現有一個接口回調的事,但是自己也沒用過這玩意,所以在園子里soso了一把,好像也沒找到interace CallBack,所以在這里給大家分享一下。如果有不正確的地方,大家一起討論,討人,希望不要誤人子弟了。呵呵.
1、少不了的Interface來實現回調的
2、當然先有一個對像CallBack,它來繼承Interface,做要被回調的方法事情,被回調來通過某些場景,或條件一但成立情況下調用的!
3、控制Controller,在某個特定條件判斷成立情況下開始調用,回調!
類圖如下:

1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 6 namespace CA_OOO_Demo001 7 { 8 /// <summary> 9 /// 定義一個回調接口 10 /// </summary> 11 interface IBack 12 { 13 void CellBackMethod(); 14 } 15 16 class CellBack : IBack 17 { 18 19 public void CellBackMethod() 20 { 21 Console.WriteLine("Thi is CellBack Method!"); 22 } 23 } 24 25 class Controller 26 { 27 public IBack CellbackObj = null; 28 29 public Controller(IBack obj) 30 { 31 this.CellbackObj = obj; 32 } 33 34 public void Start() 35 { 36 Console.WriteLine("鍵盤按下回車鍵,條件成立下執行回調方法!"); 37 if (ConsoleKey.Enter == Console.ReadKey(true).Key) 38 { 39 CellbackObj.CellBackMethod(); 40 } 41 } 42 43 } 44 45 46 class InterfaceCellBack 47 { 48 static void Main(string[] args) 49 { 50 Controller cOjb = new Controller(new CellBack()); 51 cOjb.Start(); 52 } 53 } 54 }
上面的例子感覺成了,接口策略模式了,然后再加一個實現接口類,就OK了,代碼如下:

1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 6 namespace CA_OOO_Demo001 7 { 8 /// <summary> 9 /// 定義一個回調接口 10 /// </summary> 11 interface IBack 12 { 13 void CellBackMethod(); 14 } 15 16 class CellBack : IBack 17 { 18 19 public void CellBackMethod() 20 { 21 Console.WriteLine("Thi is CellBack Method!A"); 22 } 23 } 24 25 class CellBackB : IBack 26 { 27 28 public void CellBackMethod() 29 { 30 Console.WriteLine("Thi is CellBack Method!B"); 31 } 32 } 33 34 class Controller 35 { 36 public IBack CellbackObj = null; 37 38 public Controller(IBack obj) 39 { 40 this.CellbackObj = obj; 41 } 42 43 public void Start() 44 { 45 Console.WriteLine("鍵盤按下回車鍵,條件成立下執行回調方法!"); 46 if (ConsoleKey.Enter == Console.ReadKey(true).Key) 47 { 48 CellbackObj.CellBackMethod(); 49 } 50 } 51 52 } 53 54 55 class InterfaceCellBack 56 { 57 static void Main(string[] args) 58 { 59 Controller cOjb = new Controller(new CellBack()); 60 Controller cOjb2 = new Controller(new CellBackB()); 61 cOjb.Start(); 62 cOjb2.Start(); 63 } 64 } 65 }
歡迎童鞋們討論...