Decorator Pattern C#

Problem : lets say we have Class A and Class B.

Class B source code is not available for change. & it has a method that is being called in class A. What if we need to add additional logic to method in B. What to be done?

we can have a derived class B1 from B & add our own logic in method after calling the base.Echo().

    class A

{

public B b = new B();

public void M1()

{

b.Echo();

}

}

class B1 : B

{

public void Echo()

{

base.Echo();

//New steps

}

}

/// <summary>

/// Source code cannot be touched to change

/// </summary>

class B

{

public void Echo()

{

//Line 1

//Line 2

}

}

 

But what if class B is final/Sealed???  we can achieve what achieve with inheritance using Has-a relationship.

Decorator

class A

{

public IB b = new B1();

public void M1()

{

b.Echo();

}

}

class B1 : IB

{

public void Echo()

{

new B().Echo();

//New steps

}

}

/// <summary>

/// Source code cannot be touched to change

/// </summary>

class B : IB

{

public void Echo()

{

//Line 1

//Line 2

}

}

public interface IB    {

void Echo();

}

Composite1

 

It is again a wrapper class, mostly like proxy implementing the same  interface of the actual service provider. But the only difference is that it has additional logic apart from calling the serviceProvider. where as proxy is an exact call to actual service provider.

A Decorator is a change management utility which comes in hand if we are working with classes that are final and you don;t have the source code or you are not the owner of the source code to change. so you can create a wrapper around the source code & add your own extra logics.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s