When is it necessary to use the decorator pattern? If possible, give me a real world example that is well-suited for the pattern.
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
The Streams in Java – subclasses of
InputStreamandOutputStreamare perfect examples of the decorator pattern.As an example, writing a file to disk:
Then should you require some extra functionality regarding the writing to disk:
By simply “chaining” the constructors, you can create quite powerful ways of writing to disk. The beauty in this way is that you can add different (in this example)
OutputStreamimplementations later on. Also, each implementation doesn’t know how the others work – they all just work to the same contract. This also makes testing each implementation very easy in isolation.There are plenty of “real world” examples of where the decorator pattern can be used. Off the top of my head, some examples:
Head First Design Patterns has some more “real world” examples. It seems that O’Reilly has their sample chapter, which is on Decorator Pattern, for free; Google showed up this link: PDF