What is the need for Decorator Pattern in C#?If you want
to dynamically add additional tasks to an object, then you can do it using
Decorator pattern. Here is a code sample to demonstrate how to use decorators:
class sampleClass { public virtual void sampleMethod() { Console.WriteLine(Executing sampleMethod of sampleClass); } } abstract class decoratorClass:sampleClass { protected sampleClass sampleObj; public sampleClass SampleObj { set { sampleObj = value; } } public override void sampleMethod() { if (sampleObj != null) { sampleObj.sampleMethod(); } } } class derivedDecorator:decoratorClass { public override void sampleMethod() { base.sampleMethod(); AddedActivity(); } public void AddedActivity() { Console.WriteLine(Executing additional behavior using decorators); } } class testClass { public static void Main() { sampleClass obj = new sampleClass(); derivedDecorator dObj = new derivedDecorator(); dObj.SampleObj = obj; dObj.sampleMethod(); } } Output of this code will be: Executing
sampleMethod of sampleClass
|