能用委托解決的事情,接口也都可以解決。如下所示:
public static void Main() { int[] values = { 1, 2, 3, 4 }; Util.TransformAll(values, new Squarer()); foreach (int i in values) { Console.WriteLine(i); //輸出1,4,9,16
} } public interface ITransformer { int Transform(int x); } public class Util { public static void TransformAll(int[] values, ITransformer t) { for (int i = 0; i < values.Length; i++) { values[i] = t.Transform(values[i]); } } } class Squarer : ITransformer { public int Transform(int x) { return x * x; } }
上面的例子中沒有多播,且接口中只定義了一個方法。如果訂閱者需要支持不同的轉換方式(如平方、立方),則需要多次實現ITransformer接口。
這個時候你就會發現很煩,因為每種轉換都要寫一個實現類!如下所示:
public static void Main() { int[] datas = { 1, 2, 3, 4 }; Util.TransformAll(datas, new Cuber()); foreach (int i in datas) { Console.WriteLine(i); //輸出1,8,27,64
} } ... class Squarer : ITransformer { public int Transform(int x) { return x * x; } } class Cuber : ITransformer { public int Transform(int x) { return x * x * x; } }
什么時候委托優於接口呢?
1、接口內只定義一個方法
2、需要進行多播
3、需要多次實現接口