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 Decorator Pattern says that just "attach a flexible additional responsibilities to an object dynamically". In other words, The Decorator Pattern uses composition instead of inheritance to extend the functionality of an object at runtime. The Decorator Pattern is also known as Wrapper.
Decorator design pattern is one of the structural design pattern (such as Adapter Pattern, Bridge Pattern, Composite Pattern) and uses abstract classes or interface with composition to implement.
Here are some of the properties of decorators: Decorators have the same super type as the object they decorate. You can use multiple decorators to wrap an object. Since decorators have same type as object, we can pass around decorated object instead of original.
The Decorator pattern provides a more flexible way to add responsibilities to objects than can be had with static (multiple) inheritance. With decorators, responsibilities can be added and removed at run-time simply by attaching and detaching them.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With