Saturday, January 8, 2011

Composite Pattern

You have a lots of objects in your project that are similar looking but they implement differently. This pattern allows us to treat these different objects in the same uniform manner. In a nutshell composite pattern is a basic implementation of an Interface.

Here is an example to explain this pattern in a very simple way:-
 My son was playing with wooden blocks of various shapes and that was the time I thought of this example. All these blocks have their own shape i.e. Rectangle, Square, Circle and Triangle.

If we were to implement classes to represent these objects then we will simply define 4 classes i.e. Rectangle, Square, Circle, Triangle and add their corresponding Draw method to the class definition. It becomes pretty straight forward if you just define an Interface called IShape with a method called Draw and make all the classes to implement this interface. This makes sure that all the classes  are now forced to implement Draw method.

When my son is finished playing with these shapes, he simply collects them back to a box meant to store these shapes.

ArrayList Box  = new ArrayList();
Box.Add(objRectangle)//treat everyone equal and same
Box.Add(objSquare)//treat everyone equal and same
Now I can draw them all in one simple loop
For each(IShape shape in box)   //treat everyone equal and same
{
shape.Draw();
}

Bottom-line: Ask yourself a question before implementing this pattern: "Do I have multiple similar looking objects that need a uniformity?" If the answer is yes, then go for this pattern!

No comments:

Post a Comment