The interface can solve all the problems that can be solved by delegation. As follows:
public static void Main()
{
int[] values = { 1, 2, 3, 4 };
Util.TransformAll(values, new Squarer());
foreach (int i in values)
{
Console.WriteLine(i); //Output 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;
}
}
There is no multicast in the above example, and only one method is defined in the interface. If subscribers need to support different transformation methods (such as square and cube), they need to implement ITransformer interface multiple times.
At this time, you will find it very annoying, because each transformation has to write an implementation class! As follows:
public static void Main()
{
int[] datas = { 1, 2, 3, 4 };
Util.TransformAll(datas, new Cuber());
foreach (int i in datas)
{
Console.WriteLine(i); //Output 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;
}
}
Total knot
So the question is, when is delegation better than interface?
1. Only one method is defined in the interface
2. Multicast required
3. Interface needs to be implemented multiple times