0
kicks
Fun with decorator patterns
hi,
this is my first post here. Am a little nervous thinking how my post will be. but i will try my best to take you through the topic and make you understand the topic.
the topic i will discuss is called "Decorator pattern".
i will just discuss when to use the decorator pattern and just the basic concept of decorator pattern.
What is Decorator pattern?
decorator pattern is design pattern which is used to add more functionalities to an existing class dynamically ( at runtime).
how does the concept of decroator pattern work?
the concept is usually regarded as confusing. but it is simple if you just remember the word "Wrap". we have a class "A" which is implementing and interface "Iinterface"."A" has some specific behaviours "A1","A2" etc. now we want to add a new behaviour "B1" to A. (this should be done without altering Class "A")
we can do it in a simple way
Create a class "B" implementing "IInterface"."B" will have the behaviour "B1".
create a class which will help any "IInterface" implementor to wrap around any other "IInterface" implementor. This is our decorator.
now at runtme create an instance of "A".lets call it "objA".
now create an instance of "B",lets call it "objB".
use the use the decorator to help objB so that it can wrap around objA.
now the decorator is nothing but objB which will have objA inside it.
so the decorator now has the funtionality of both objB and objA so it will emit the behaviour "A1","A2","B1".
note that we did not have to change the class A at all.
now if we want to add another functionality "C1" to this decorator object(having objB and objA),how will we do it?
we can do it, if we make the Decorator class implement "IInterface".
recollect that the purpose of the Decorator is to help any "IInterface" implementor to wrap around any other "IInterface" implementor.
now we can have any decorator wrapped in any other decorator.
hope i was clear.
i will give an example in my next post.