Before going to describe my problem first,I would like to define definitions of Decorator and Extension method
Decorator
Attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality
Extension method
Extension methods enable you to “add” methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type
I have following code snippet in c#
public interface IMyInterface
{
void Print();
}
public static class Extension
{
public static void PrintInt(this IMyInterface myInterface, int i)
{
Console.WriteLine
("Extension.PrintInt(this IMyInterface myInterface, int i)");
}
public static void PrintString(this IMyInterface myInterface, string s)
{
Console.WriteLine
("Extension.PrintString(this IMyInterface myInterface, string s)");
}
}
public class Imp : IMyInterface
{
#region IMyInterface Members
public void Print()
{
Console.WriteLine("Imp");
}
#endregion
}
class Program
{
static void Main(string[] args)
{
Imp obj = new Imp();
obj.Print();
obj.PrintInt(10);
}
}
In the above code I am extending interface without modifying the existing code,and these two methods are available to derived class. So my question is this: Is the extension method a replacement of the decorator pattern?
A extension method is really just syntactic sugar for calling a static method.
While with a decorator you could actually change the behaviour of your decorated class, a extension method could only alter properties or call methods on your class, just like an “ordinary” static method.
Decorator pattern is actually definied as using a wrapper to alter behaviour, which a extension method clearly doesn’t do.