Monday, August 29, 2011

Solution to Decorator Pattern Exercises of C# 3.0 Design Patterns

Decorator Pattern (this description is directly taken from the book C# 3.0 Design Patterns by Judith Bishop)

The role of the Decorator pattern is to provide a way of attaching new state and behavior to an object dynamically. The object does not know it is being “decorated,” which makes this a useful pattern for evolving systems. A key implementation point in the Decorator pattern is that decorators both inherit the original class and contain an instantiation of it.

Image is taken from

Click here to download my solution to the exercises.

These are the exercises from the book with a few comments oh how I coded my solution for each:

1. Assume that the Photo class was written with Drawer as a plain (not virtual) method and it cannot be altered. Reconstruct Example 2-2 so that it works under this constraint. (Hint: use an interface as in the theory example.)

2. Add to the Photo Decorator system a second type of component called Hominid. Use the drawing methods for ovals and lines to draw an approximation of a person. Then, use the same two  decorators—Tag and Border—to decorate Hominid objects.

3. Add other event handlers to the constructors of the decorators, together with additional behavior. For example, an OnClick event could cause a tag to appear, rather than having it appear  automatically.

4. Decorate the Console class so that Write and WriteLine methods are trapped and the output is reformatted for lines of a given size, avoiding unsightly wraparounds. Test your decorator with the program in Example 2-1.
The Console class cannot be inherited because it is static. What I did here is I created a constructor that has a parameter that takes a TextWriter. The client needs to pass the Console.Out as parameter to the ConsoleDecorator's constructor.

5. Write a program that decorates the Stream class and shows how much of a file has been read in, using a trackbar.

I used a ProgressBar instead of a TrackBar.
I created an event that will be raised each time a character is read by the TrackStream.Read() method.

6. Write a program that decorates the Stream class and asks for a password before allowing reading to continue.

7. Write a program that decorates a text message with a simple cipher. Include a second decorator that transforms the encrypted message back to plain text.
I used a simple cipher called the Caesar's Cipher