Posts Tagged ‘structural patterns’

[tweetmeme source=”aabdulmoniem” only_single=false]

We have discussed in our previous post the decorator pattern’s role, and giving a very detailed illustration about it. Also, we have discussed its design varieties and clarified when to use each design and why.

Today, we will complete our discussion about decorator pattern. We will talk deeply about different examples from the real world cases to give you more deep understanding of this pattern. Also, we will discuss when to use this pattern in real world situations.

We will demonstrate first a simple example and then move on to a more complicated ones and more variations.

1 – Example: Use Case Diagram Tool

Use case diagram is one of the fundamental diagrams of the unified modeling language (UML).  We use the use case diagrams to describe all the use cases a user can interact with within an application.

Here, we will start to build a simple (Really, it is a very simple, just for demonstrations purposes) use case diagram tool.

If we look more thoughtfully into the available shapes that can be drawn in a use case diagram, we will find them to be 3 main shapes:

  1. Actors.
  2. Use cases.
  3. Arrows (which represent relationships between actors, or between use cases or between actors and use cases).

But a more deep look, we will find that each shape has a different look in a different situations.

As described in the following diagram, some of the variations that could be applied to any shape during drawing process of use case diagrams:

The challenge here that we want to build an application that covers all the variations available and with an ability to add more shapes in futures in case of any updates happens to UML.

Here comes the magic of the decorator pattern. Let’s get started:

Analyzing the last diagram shows us that we have 3 main shapes with different variations. Variations means here decorators which can be applied to different shapes to show us the right final shape.

More analyzing, we are noticing that we have some kind of hybrid decorators like for example, dotted line with a tag. In fact, they are two decorators tag decorator and dotted line decorator.

Let’s first start with one shape and then we will elaborate on this.

IShape interface and Actor class:

IShape Interface:

public interface IShape
     Bitmap Draw();

Actor Class:

public class Actor : IShape
     public Bitmap Draw()
         Bitmap image = new Bitmap(200, 200);

         using (Graphics graphics = Graphics.FromImage(image))
              using (Pen blackPen = new Pen(Brushes.Black))
                   // Drawing head
                   graphics.DrawEllipse(blackPen, 100, 20, 20, 20);

                   // Drawing backbone
                   graphics.DrawLine(blackPen, 110, 40, 110, 80);

                   // Drawing arms
                   graphics.DrawLine(blackPen, 110, 55, 130, 55);
                   graphics.DrawLine(blackPen, 110, 55, 90, 55);

                  // Drawing legs
                  graphics.DrawLine(blackPen, 110, 80, 130, 100);
                  graphics.DrawLine(blackPen, 110, 80, 90, 100);

        return image;

If we try now to use this class with a windows forms application in .NET for example you will write just like the following code after dragging a picture box into the form:

Actor actor = new Actor();
pictureBox1.Image = actor.Draw();

Run the project, you will see:

Now we need to add some sugar, so let’s add a decorator called TagDecorator which will be responsible for adding tags (titles) to any shape.

Here is the class diagram (following the guidelines of decorator patterns):

TagDecorator Class:

public class TagDecorator : IShape
     private IShape _shape;
     private string _tag;

     public TagDecorator(IShape shape, string tag)
          _shape = shape;
          _tag = tag;

     public Bitmap Draw()
         // Getting the actor shape without tags
         Bitmap image = _shape.Draw();

         // Writing the tag under the actor shape
         using (Graphics grahpics = Graphics.FromImage(image))
              grahpics.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias;
              StringFormat stringFormat = new StringFormat
                   Alignment = StringAlignment.Center,
                   LineAlignment = StringAlignment.Center
              grahpics.DrawString(_tag, new Font("Times New Roman", 12), Brushes.Black, new RectangleF(10, 110, 200, 20), stringFormat);

         return image;

Let’s try to draw this decorated actor to the form. So we will write this code:

Actor actor = new Actor();
TagDecorator actorTag = new TagDecorator(actor, "User");
pictureBox1.Image = actorTag.Draw();

And see the output:

Now let’s make things more complicated, I will just give you the concepts and let you try to implement them.

What if we want to add more shapes, simply we will use the following diagram:

What about more decorators?!

Go, and try to build you own diagramming tool.

2 – Real World Examples

Now we will demonstrate some real world examples may be we are using in a daily basis but we don’t know.

In a very good article by Rob Pierry, he discussed when a decorator pattern has been used within .NET. He Said:

“Any useful executable program involves either reading input, writing output, or both. Regardless of the source of the data being read or written, it can be treated abstractly as a sequence of bytes. .NET uses the System.IO.Stream class to represent this abstraction. Whether the data involves characters in a text file, TCP/IP network traffic, or something else entirely, chances are you will have access to it via a Stream. Since the class for working with file data (FileStream) and the class for working with network traffic (NetworkStream) both inherit from Stream, you can easily write code that processes the data independent of its origins. Here’s a method for printing out some bytes from a Stream to the console:

public static void PrintBytes(Stream s)
     int b;
     while((b = fs.ReadByte()) >= 0)
         Console.Write(b + " ");

Reading a single byte at a time is typically not the most efficient way to access a stream. For example, hard drives are capable of (and optimized for) reading continuous blocks of data from the disk in a big chunk. If you know you are going to be reading several characters, it is better to read a chunk from the disk all at once and then consume the chunk from memory byte by byte. The Framework includes the BufferedStream class for doing just that. The constructor for BufferedStream takes as the parameter whatever stream you would like buffered access to. BufferedStream overrides the main methods of Stream, such as Read and Write, to provide more functionality. Since it is still a child class of Stream, you can use it the same as any other Stream (note that FileStream includes its own buffering capabilities). Similarly, you can use System.Security.Cryptography.CryptoStream to encrypt and decrypt Streams on the fly, without the rest of the application needing to know anything more than the fact that it is a Stream.

This ability to dynamically attach new functionality to objects transparently using composition is an example of the Decorator pattern”.

This is valid also for Java developers as well as far as I know in java.io namespace.

Let’s also demonstrate a more general real examples:

Here are four ways the Decorator pattern is used in the real world (Excerpt from C# 3.0 Design patterns):

  • As our small example illustrated, the Decorator pattern fits well in the graphics world. It is equally at home with video and sound; for instance, video streaming can be compressed at different rates, and sound can be input to a simultaneous translation service.
  • At a more mundane level, decorators abound in the I/O APIs of C# as illustrated.
  • In today’s world of mobile devices, web browsers and other mobile applications thrive on the Decorator pattern. They can create display objects suitable for smaller screens that include scroll bars and exclude banners that would be standard on desktop display browsers, for example.
  • The Decorator pattern is so useful that there are now actual Decorator classes in .NET 3.0. The one in System.Windows.Controls “provides a base class for elements that apply effects onto or around a single child element, such as Border or Viewbox.”

3 – When to use?

When you have:

  • An existing component class that may be unavailable for subclassing.

Or When you want to:

  • Attach additional state or behavior to an object dynamically.
  • Make changes to some objects in a class without affecting others.
  • Avoid subclassing because too many classes could result.

4 – Finally

At last, we have finished demonstrating this pattern. Our next one is Proxy pattern. So, be with us 🙂


Read Full Post »

[tweetmeme source=”aabdulmoniem” only_single=false]

New day, a new pattern. Today we will start to discuss structural patterns deeply starting with the Decorator pattern.

Really, I am trying to collect as many resources as possible for this huge topic to be valuable and to add something wasn’t published before so I am in parallel reading the famous book Gang of four, also C# 3.0 Design Patterns by O’Reilly, and some other tutorials and stuff.

I liked the way that O’Reilly book takes to discuss each pattern so I will reuse the headlines for each pattern but I will try to add more value to the content. So, let’s start discussing Decorator pattern.

1 – Role

Decorator pattern’s role is to provide a way to add new state and behavior dynamically. The decorated object doesn’t know that it is being decorated which is very useful for evolving systems.


2 – Illustration

As its name suggests, it is used to add or remove (decorate) objects at runtime with new state or new behavior. The best example that I have ever read to illustrate this pattern is the photo management system which lets you edit some aspects of the photo like adding new border, tag, or caption.


Consider we have a photo and we want to add a border to it, may be a border and caption, or may be caption only. If you just think a bit, you will find that a combination of photo and border makes another object which is photo with border. So every combination may result in a different (unknown) object at runtime which means we can have endless ways to customize the photo.

Also, I liked the illustration of the Gang of four book which is:

Suppose we have a TextView object that displays text in a window. TextView has no scroll bars by default, because we might not always need them. When we do, we can use a ScrollDecorator to add them. Suppose we also want to add a thick black border around the TextView. We can use a BorderDecorator to add this as well. We simply compose the decorators with the TextView to produce the desired result.


The beauty of this pattern is that:

  • The original object is unaware of any decorations.
  • There is no one big feature-laden class with all the options in it.
  • The decorations are independent of each other.
  • The decorations can be composed together in a mix-and-match fashion.

3 – Design

Reading here and there about this pattern, I have concluded that there are some minor variations in its design because of the language features you are implementing the pattern with. But the main guidelines remains.

I will start with a very general design (mentioned in the Gang of four book) then I will go through other variations step by step:

Basic Design


  1. ConcreteComponent
    • An original class of objects that can have operations added or modified (there may be more than one such class).
  2. Component
    • The base class that identifies the classes of objects that can be decorated (ConcreteComponent is one of these).
  3. Decorator
    • The base class that identifies the common operations or state in the decorator classes and it inherits from the Component base class.
  4. ConcreteDecorator
    • A class that inherits from the Decorator base class and adds state and/or behavior (there may be more than one such class).
  5. Operation
    • An operation in Component objects that can be replaced (there may be several operations).


Looking into the previous players, we will see that we have two base classes Component and Decorator. Most of the variations in this pattern’s design results from changing or replacing those two classes as we will see now.

Use this basic design if:

  1. You are not the creator of this object structure, like that you have already made structure and you want to decorate it.
  2. You are the one who creates this structure but your using C++ or any language doesn’t support interfaces.
  3. You have default implementation in both Decorator and Component base classes.
  4. You have multiple decorators have common behavior and/or state defined in Decorator base class.

Variation 1


As you notice from the previous diagram, you can see that we have replaced the Component base class with an interface IComponent. Here we have to mention that in old days when Gang of four book was written, authors had implemented the patterns using C++ which doesn’t contain interfaces. In modern languages today like C# or Java contain the concept of interfaces.

I recommend always to use interfaces not abstract classes as long as you don’t have default implementation you want to add for all the subclasses.

Use this variation if you are using a language contains the interfaces concept and:

  1. You don’t have any default implementation in the Component base class and you have default implementation for the all concrete decorators.
  2. You are the one who is creating this object structure from scratch and have full control of it.
  3. You have multiple decorators have common behavior and/or state defined in Decorator base class.


Variation 2


Use this variation if you are using a language contains the interfaces concept and:

  1. You don’t have any default implementation in both Component base class and Decorator base class.
  2. You are the one who is creating this object structure from scratch and have full control of it.
  3. You have multiple decorators have common behavior and/or state defined in the IDecorator interface.

C# 3.0 Design Patterns by O’Reilly notified that IDecorator in C# has no purpose. And I didn’t get this note until now, but I see that if you have common behavior and/or state that you want to be in all decorators then you have to use either interface or a base class and depending in your situation you can select what is more appropriate from the other variations.

Variation 3


Use this variation if you are using a language contains the interfaces concept and:

  1. You don’t have any default implementation in both Component base class and Decorator base class.
  2. You are the one who is creating this object structure from scratch and have full control of it.
  3. You don’t have common behavior and/or state between decorators.

Common Design Guidelines

As we saw in the last four variations, you will see some common guidelines that I want to concentrate on them:

  1. All components must have a base class or interface.
  2. All decorators must be components. In other words, all decorators must inherit Component base class or implement IComponent interface.
  3. All decorators must wrap a component (Decorator must have a member of type Component or IComponent).

4 – Implementation

I will try here to give you a simple implementation of the decorator pattern. I will discuss how to implement the decorator pattern in general without considering any challenging examples or complicated scenarios.

I will use variation 3 to give you a simple implementation using the following UML class diagram:

Using C# or another candidate language, First we have to create IComponent Interface which will contain only one operation.

public interface IComponent
   void Operation();

Then we will create a Component class which will implement IComponent interface.

public class Component : IComponent
   public void Operation()
      Console.WriteLine("I love reading books.");

Now we want to decorate the Component object with a decorator. So let’s create one decorator class which will wrap an IComponent object and Implement the same interface IComponent interface.

public class DecoratorA : IComponent
   private IComponent _component;

   public Decorator(IComponent component)
      _component = component;

   public void Operation()
      Console.WriteLine("And I love playing football.");

Another decorator class:

public class DecoratorB : IComponent
   private IComponent _component;

   public Decorator(IComponent component)
      _component = component;

   public void Operation()
      Console.WriteLine("And I love fishing.");

Now let’s build the client which will be a simple console application which will consume our Component and will decorate it.

using System;

namespace DecoratorPatternImplementation
   class Program
      static void Main(string[] args)
          Console.WriteLine("=== Original Component ===");
          IComponent component = new Component();

          Console.WriteLine("=== Original Component Decorated by DecoratorA ===");
          IComponent decoratorA = new DecoratorA(component);

          Console.WriteLine("=== Original Component Decorated by DecoratorB ===");
          IComponent decoratorB = new DecoratorB(component);

          Console.WriteLine("=== Decorated Component By DecoratorA Decorated by DecoratorB ===");
          IComponent hybridDecorator = new DecoratorB(decoratorA);

Run the console application and here is the output:

=== Original Component ===
I love reading books.

=== Original Component Decorated by DecoratorA ===
I love reading books.
And I love playing football.

=== Original Component Decorated by DecoratorB ===
I love reading books.
And I love fishing.

=== Decorated Component By DecoratorA Decorated by DecoratorB ===
I love reading books.
And I love playing football.
And I love fishing.

Press any key to continue . . .

We have to point out to some important notices here:

  1. You can decorate a decorated component as we have seen in last example.
  2. Decorator pattern gives you the ability to mix and match between decorators.
  3. Decorators do not need any advanced language features; they rely on object aggregation and interface implementation.

5 – Finally

We are now ready to go deeply into this pattern by investigating some real world examples. Keep up, wait for the next post.

Read Full Post »

[tweetmeme source=”aabdulmoniem” only_single=false]

I am gonna start a new series for a very interesting topic which is object oriented design patterns. Yeah, I hear some of you are saying now: “Hey, did you ever hear about something called gang of four?!!”. Really, I do. But I am not coming here to reinvent the wheel. I am trying here to add some value on this interesting topic by diving deeply into it.

Really, there are enormous topics we can discuss about every design pattern but the most important one that I think we should discuss deeply and we should add to the design pattern empire is how to use it in real applications?! Yeah, we will discuss all the basics of each design pattern but for the practical part I didn’t find a real complete one example you can rely one or I think that all what I have seen in books, articles and forums not a real complete example.

As you may know, design patterns are divided into three categories with 23 design patterns as defined in the famous book Gang of four, and here are the categories:

  1. Structural Patterns
  2. Creational Patterns
  3. Behavioral Patterns

I have chosen to start with structural patterns. I will just give you an overview of this category here and we will continue to discuss each design pattern in this category in upcoming posts.

What are Structural Patterns?

Simply, Structural patterns are concerned with how classes and objects are composed to form larger structures.


  • Add new functionality dynamically to existing objects, or remove it.
  • Control access to an object.
  • Create expensive objects on demand.
  • Enable development of the interface and implementation of a component to proceed independently.
  • Match otherwise incompatible interfaces.
  • Reduce the cost of working with large numbers of very small objects.
  • Reorganize a system with many subsystems into identifiable layers with single entry points.
  • Select or switch implementations at runtime.
  • Simplify the interface to a complex subsystem.
  • Treat single objects and composite objects in the same way.

Design Patterns Included

  1. Decorator (Part 1, Part 2)
  2. Proxy (In Press …)
  3. Bridge
  4. Composite
  5. Flyweight
  6. Adapter
  7. Façade

When to use it?

Structural patterns can be employed while a system is being designed, or later on during maintenance and extension. In fact, some of them are specifically useful in the post-production stages of the lifecycle of a software system, when changes are introduced that were not foreseen and when even the interfaces between components need updating. Thus, sometimes when you want to add functionality, you will be working with existing classes that cannot be changed. The Decorator pattern is useful here. Alternatively, you might be able to design a whole system from scratch so that it works in a particularly usable way, with the Composite pattern.

Next Step

We will start by discussing Decorator pattern. Stay with us.

  • Addison Wesley – Gang of Four – Design Patterns, Elements of Reusable Object Oriented Software
  • O’Reilly – C# 3.0 Design Patterns

Read Full Post »

%d bloggers like this: