You are on page 1of 45

Decorator Pattern (A Layman to Laymen)

Introduction
A friend of mine always used to say that the toughest part of learning any programming
discipline is to run the Hello World. After that, everything is easy. Years later, I realized how
right he was. This is the basic goal behind this series on design patterns, to help out people
getting started with these. It especially targets those who have strong OOP concept but are
struggling with design patterns, and cant figure out how to apply them in their designs. I dont
claim to write some comprehensive reference on different design patterns, but I do hope that this
series will help you getting started with these. Designs patterns cant be tied to a specific
language. Even though I provide most of my code examples in C#, I will try avoiding C# specific
constructs as much as possible, and hence targeting maximum readers, especially the ones
working in languages influenced by C++ object model.
Decorator pattern allows us to add additional behaviors to the objects dynamically. Just like in
my previous article, Strategy Pattern Primer, we will first go through a scenario. We will also look
at the alternate approaches, which will help us realize the real power of this design pattern, and
the flexibility it offers.
The Thought Process
The scenario we will follow today may not be very realistic and sometimes pretty weird, but it will
help us understand the concepts and power underlying this pattern. The goal is to add the
functionality of storing messages coming from different sources on the hard disk in the form of
text files. So first of all we defined the intention (interface) and then implemented it.
IMessageWriter, and IMessageReader interfaces for writing and reading messages
respectively, as well as their implementations are given below.
Collapse | Copy Code
interface IMessageWriter
{
string Message { set; }
void WriteMessage(string filePath);
}
class MessageWriter : IMessageWriter
{
private string message;

#region IMessageWriter Members

public string Message
{
set { this.message = value; }
}
public virtual void WriteMessage(string filePath)
{
File.WriteAllText(filePath, this.message);
}

#endregion
}

interface IMessageReader
{
string ReadMessage(string filePath);
}

class MessageReader : IMessageReader
{
#region IMessageReader Members

public virtual string ReadMessage(string filePath)
{
if (File.Exists(filePath))
return File.ReadAllText(filePath);
else return null;
}

#endregion
}
The message will be stored in the Message property while WriteMessage of MessageWriter is
just writing it on the file path passed to it. Similarly MessageReaders function ReadMessage()
will read it back from the file and return it as a text string. Lets say you receive new
requirements from the customer.
1. For certain messages, we need to validate the user before reading and writing the file.
2. For some messages, we want them to be saved encrypted so no one would be able to read it
from the file. But we need to save this encrypted message in base4 encoded string.
3. For some messages, we need both of these functionalities.
Pretty weird haa . First we will analyze different solutions without using Decorators. This will
make us realise how powerful this simple design pattern is.
Classical Solutions
You decide to use inheritence as it will allow you to build upon the base behavior. You choose to
implement the encryption behavior in EncryptedMessageWriter, derived from
MessageWriter.

Similarly you derive SecureMessageWriter (class for user validation) from
EncryptedMessageWriter.

Now we can Write encrypted messages as well as encrypted messages with user validation. What
about the case where we need to write simple text message without encryption but with user
validation. You can use some dirty trick of placing some decision making code in
EncryptedMessageWriter which will make it skip encryption when not needed. Lets say you
still choose this option. How about a different sequence of operations, i.e., we want to encrypt
first, then we will validate, and if not validated then we will do something else with the based64
encoded encrypted message. Obviously this case cannot be handled with the above hierarchy.
And who can stop the customer from requesting more features like some messages should be
digitally signed, larger messages should be compressed with or without encryption as required,
for some messages, after writing them on disk, you must enter the file path and timestamp in
MessageQueue for some other application to read, or even in the database. And so on and on
and on.
To assess the gravity and complexity of the situation youre in, lets focus on just validation,
forgetting about the details of hierarchy. Currently, we have the implementation of validation in
case of encrypted message. Now we need to have the same functionality in many other cases,
e.g., for CompressedMessageWriter, DigitallySignedMessageWriter, etc. The only choice
you have is to implement SecureCompressedMessageWriter,
SecureDigitallySignedMessageWriter etc. Similarly for plenty of other combinations like
encrypted message compression, simple message compression, and so on. Damn, you are really
in Sub Class Hell.
The second solution is to write a pretty hefty MessageReader and keep on adding all the
functionality as the requirement arrives. Increasing its complexity and making it hard to maintain,
over time. The most unrecommended approach.
A third solution might be a combination of the above two, which may alleviate the problem but
wont take it away.
Decorator Pattern Enters The Scene
This is exactly the kind of problem decorator pattern solves. If you look carefully at the above
solution involving inheritence, you will realise that the root of the trouble is the static
relationship introduced by inheritence. This relationship is embedded into the classes which
cannot be changed at runtime. Decorators replace this relationship with containment, an object
relationship which is much more flexible and can be updated at runtime.
First, lets see what decorator pattern actually is. Following is the class diagram for decorator
pattern.

The four participants are:
1. Component: Interface for the objects that can have responsibilities added to it dynamically. In
our case IMessageWriter and IMessageReader.
2. ConcreteComponent: Defines an object implementing Component interface. This is the object
that is going to be decorated, but it doesnt have any knowledge of decoration. The person
implementing the decorator may not even have the access to the source code. In our case
MessageWriter and MessageReader.
3. Decorator: Maintains a reference to the Component object, and defines an interface that
conforms to the Component interface. So it contains a reference to the base behavior, and also
implements the same interface, hence can be treated as the Component itself. The client code
expecting the Component will deal with Decorator without even noticing the difference.
4. ConcreteDecorator: This actually adds responsibility to the component. The class that inherits
from Decorator and may add some additional specific functionality in the form of new public
methods.
Up to now we have two things: Component, the base behavior, in our case IMessageWriter and
for reading IMessageReader, and ConcreteComponent, our implementations of writing and
reading behaviors, MessageWriter and MessageReader respectively.
Now here are our implementations of SecureMessageWriter and EncryptedMessageWriter.


Where the Hell is your Decorator?????
I just said there are four participants in this pattern, I have shown you Component
(IMessageReader, IMessageWriter), ConcreteComponent (MessageReader, MessageWriter)
and ConcreteDecorators (SecureMessageWriter, EncryptedMessageWriter). But where is
the Decorator? In our case, we are just adding to already existing behavior and introducing no
new behavior. We are not changing the hierarchy either. In that case, we can ignore
implementing Decorator and follow the main hierarchy. I am not showing the Reader classes as
these are just the reverse process.
What Have We Achieved
Now, when I need a simple message writing with user validation I will do.
Collapse | Copy Code
IMessageWriter msgWriter = new SecureMessageWriter(new MessageWriter());

I am decorating the MessageWriter with SecureMessageWriter and it will now validate user
before writing the message on the disk. In case of needing Encrypted message writing along with
Validation, I will do:
Collapse | Copy Code
IMessageWriter msgWriter =
new SecureMessageWriter(new EncryptionMessageWriter(new MessageWriter()));
1. Decorators have saved us from making a complex base class, with plenty of code, which wont be
needed in most of the instances.
2. They allow us to make different combinations, and sequences of different behaviors, which was
not easily possible otherwise.
3. Rather than implementing different subclasses for each different behavior and combination, we
have implemented each required behavior separately which we can add as needed.
Back to the Real World
In this section, we will see some real world examples of the usage of Decorator pattern.
Synchronization Wrappers
People who used good old collection classes in .NET, like Queue, ArrayList, etc., may still
remember the function synchronized(collection), exposed by many of these classes. It takes the
collection instance itself as a parameter and returns a synchronized collection. Collection classes
themselves are not synchronized, but what this method actually returns is a decorator derived
from the collection class itself. For example, in the code below, when we call
Syncrhonized(al), we will receive an instance of SyncArrayList, a class derived from
ArrayList.
Collapse | Copy Code
ArrayList al = new ArrayList();
al = ArrayList.Synchronized(al);
//Now al can be treated just as ArrayList
//but actually it's an instance of SyncArrayList
//which is derived from ArrayList
And SyncArrayList will store the ArrayList passed in the property _list and will override
different instance methods of the ArrayList this way.
Collapse | Copy Code
public override int Add(object value)
{
lock (this._root)
{
return this._list.Add(value);
}
}
A Word Of Caution
While creating your own synchronization wrappers this way, be careful of the phenomenon called
self-deadlock, which means a thread already having a lock will enter another method (or in the
same method in case of recursion) where it will try to obtain the lock on the same object again. In
Windows whether you use .NETs implementation of Monitors, or kernel level named or unnamed
mutexes, all are re-entrant i.e. recursive. So you will not face this problem but when programming
in other environments like Linux where default mutex type is Fast mutex, a non-recursive mutex,
your code may become a victim of self-deadlock. In case of using a semaphore even on
Windows, it also has no sense of ownership, and gives you this problem if you are not careful. Of
course for a binary semaphore i.e. with n=1, only on second attempt you will be in a self
deadlock.
On the same model, you may implement a read-only wrapper of you collection classes. And
unlike what we have seen till now, they rather than adding functionality to the classes, will take
away some. For example in overridden Add() method one may throw
OperationNotSupportedException. .NET offers ReadonlyCollection<T> which is a
wrapper around generic list. Java provides unmodifiable wrappers, e.g.,
unmodifiableCollection, unmodifiableSet, etc.
In Java, you also get synchronization wrappers for many collection types, e.g.
Collapse | Copy Code
List<t> list =
Collections.synchronizedList(new ArrayList<t>());
IO in Java and .NET
Javas java.io package and .NETs Stream classes employ this pattern. I will not go into the
details of their underlying implementations. In .NET, Stream, which is an abstract class, is
providing the base behavior (our Component), whereas classes like FileStream, MemoryStream
are ConcreteCompents and classes like BufferedStream, CryptoStream etc. are Concrete
decorators, which like Filestream, and MemoryStream are derived from abstract Stream class.
You can clearly notice that their implementation is missing the Decorator as well.
Similarly in Java BufferedReader and FilterReader are decorators of Reader, whereas
BufferedReader is further decorated by LineNumberReader, and FilterReader by
PushbackReader.
What's the Catch
This pattern allows us to provide the extensibility point in your implementation. As you might
have noticed, while implementing my decorators I never even touched my component classes. So
even if one doesnt own a class, one can decorate it to add new behaviors dynamically and even
recursively. This additional behavior might be added before or after the base behavior, or this
behavior might be blocking it. The decorators can provide new methods and even new properties
as you can see in the class diagram. But there are some problems associated with decorators.
1. The programmer who is going to use decorators must understand their intention; otherwise he
may end up using some senseless combination or sequence. For example in our scenario if the
programmer defines the sequence in this way: message will be compressed, then encrypted, and
then validated, it will be a bit senseless. In real life scenarios, the results might be disastrous for
some combinations or ,sequences.
2. Testing a decorator class will require providing a mock of decorated class. Since we havent yet
covered testing, so I will not discuss it
3. Also this pattern puts some responsibility on the base behavior designer. Although it's perfectly
legitimate to add new properties or public methods in the decorator, but this way it will lose
the flexibility of being handled by the base reference, and you will need to use the concrete
instance
Now Some Clearances
I thank all who provided me the feedback on my previous article on strategy pattern. That has
guided me writing this one. Many have accused me of oversimplification in one way or other.
Well I assert that I havent oversimplified anything. These words might be a bit misleading. What I
am trying to say is that their feedback was correct, as simplification was my goal. But
oversimplification is a bit harsh. Those people arent totally wrong, as I have avoided mixing up
design patterns with programming idioms. What I am presenting in this series is the underlying
principles and a guideline on where to apply the pattern. The underlying principles are simple; its
the problem that gives you hard time. Recognizing parts of the problem that are candidate for
design patterns might be tricky and requiring experience. Sometimes you wont even realize that
a certain piece of code is a good candidate for applying some design pattern, till many cycles of
refactoring have been performed. This gives us another reason for analyzing the problem and
recognizing the different design patterns to save us from plenty of future refactoring as they are
already the result of heavy refactoring. However that feedback helped me a lot, and in future I
will try covering languages specific implementations too (provided Ill have enough time). The
next article will be on Creation patterns covering Simple Factory, Factory Method, Abstract
Factory and Builder. Once again your feedback is more than welcome, identifying the areas where
i couldn't clear things up, or the points of improvement, thanks.

Learn Decorator Design Pattern in Easy Steps
Introduction
Kartoon Kompany approaches you for re-designing their application on the famous Kelvin and
Hoppes comic strip!
A quick recap about Kelvin: he is a moody brat with an extremely wild and vivid imagination. His
behavior and reactions are completely different and unpredictable, and is based on his current
fantasy he has dreamed up. He thinks up imaginary worlds and situations, like a spaceman
battling Zorgs, TracerBazooka Film Noir detective, imagines he is a T-rex, so on and so forth.
This is their current design:
Collapse | Copy Code
class Kelvin
{
public:
virtual void MisBehave()
{
std::cout<< "Hi, I am Kelvin the Great!\n";
//yeah, this is just simply writing text to console.
//But imagine if this was some functionality.
//Lets assume writing text to keep things simple
}
};

class SpacemanDecorator: public Kelvin
{
public:
virtual void MisBehave()
{
//when kelvin is spaceman he does something different
std::cout<< "The fearless Spaceman Kpiff battles with the Zork!!!\n";
}
};

class DinoDecorator: public Kelvin
{
public:
virtual void MisBehave()
{
//when kelvin is a Dinosaur, imagine the chaos!
std::cout<< "Kelvin the terrible T-Rex runs rampant in Jurassic park!\n";
}
};

class TracerBazookaDecorator: public Kelvin
{
public:
virtual void MisBehave()
{
//Film-Noir fantasy behavior
std::cout<< "TracerBazooka: Here's looking at you kid.\n";
}
};
Now, Kartoon Kompany has a problem: for the next comic strip, they want to combine a T-Rex
episode and a Spaceman episode in one strip. Fans go wild with anticipation.
How do we address this? Simple, let's create a DinoSpaceman behavior class where Kelvin acts
accordingly, right?
Do you see how easily this could explode into a plethora of subclasses? What about a T-Rex-
Spaceman episode? What about a Tracer-TRex episode? Think sub-class nuclear explosion. And
we are not even talking of adding new classes like WithSusie, SnowBallFights,
SantaLetters, etc.
This is the problem Kartoon Kompany approaches you with. How do you solve this design issue?
Inheritance, though powerful, is not the panacea for Kartoon Kompanys woes. The problem with
the current design is, because all behaviors are defined in sub-classes, we need to keep adding
lots of sub-classes, and that is especially difficult considering Kelvins unimaginable imagination.
Enter Decorator Design Pattern (on an F-16
figher jet, with guns blazing)
Okay, so inheritance is out. The problem is that we are trying to define all of Kelvins behavior at
compile time. Wouldnt it be great if we could specify Kelvins behavior at run-time? Then we
dont have to sub-class, but could use composition at run-time to define Kelvins reactions
(authors note: dont worry if this doesnt make sense now, read on).
The Decorator Design Pattern does that for us! Short and sweet, Decorator does following:
Adds behavior to a class dynamically, at run-time. This is in contrast to inheritance, which binds
behavior statically, i.e., at compile time.
Is an alternative to sub-classing.
Enough theory, lets take a plunge and see how the Decorator Design Pattern helps Kelvin.
Apply the simplest of Design Principles: encapsulate and separate what varies. Since the
combination of various Kelvin imagination\behavior varies, let's take them out of the Kelvin class
hierarchy. I.e., TRex, Spaceman, TracerBazooka should no longer be derived classes of the
Kelvin superclass. Since the function MisBehave() is common, let's create a common base
class, which will be our brand new decorator base class!
Collapse | Copy Code
//derive from Kelvin so that interface of decorator is same.
//This makes life easy on the client (caller) side
//this will be our base decorator class. We are adding
//new behavior to Kelvin thru composition
class KelvinDecorator: public Kelvin
{
public:

//ctor taking in component to decorate (i.e. Kelvin) as argument.
//We need a Kelvin in order to decorate\add new behavior,
//there is no KelvinDecorator without Kelvin!
KelvinDecorator(Kelvin *kelvinArgument): KelvinComponent(kelvinArgument)
{ }

//overload common interface from Kelvin
virtual void MisBehave()
{
//just ask kelvin to misbehave! The wonder of virtual keyword
//and polymorpishm will call correct derived class,
//either Decorator or main component
kelvinComponent->MisBehave();
}

private:

//Kelvin component, which we need to decorate
Kelvin *kelvinComponent;
};
Now, with this base decorator as the super\base class, we create the Kelvin Decorator specific
classes:
Collapse | Copy Code
// Just derive from our Decorator base-class and overload Kelvins interface
class SpacemanDecorator: public KelvinDecorator
{
public:

SpacemanDecorator (Kelvin *kelvin): KelvinDecorator(kelvin)
{ }

virtual void MisBehave()
{
// call previous decorator
KelvinDecorator::MisBehave();

//now add this decorator's additional functionality
std::cout<< "The fearless Spaceman Kpiff battles with the Zork!!!\n";
}
};

class DinoDecorator: public KelvinDecorator
{
public:
DinoDecorator (Kelvin *kelvin): KelvinDecorator(kelvin)
{ }

virtual void MisBehave()
{
// call previous decorator
KelvinDecorator::MisBehave();

//now add this decorator's additional functionality
std::cout<< "Kelvin the terrible T-Rex runs rampant in Jurassic park!\n";
}
};

class TracerBazookaDecorator: public KelvinDecorator
{
public:
TracerBazookaDecorator (Kelvin *kelvin): KelvinDecorator(kelvin)
{ }

virtual void MisBehave()
{
// call previous decorator
KelvinDecorator::MisBehave();

//now add this decorator's additional functionality
std::cout<< "TracerBazooka: Here's looking at you kid.\n";
}
};
Thats it! Youve implemented the Decorator Design Pattern! Now, we let the beauty of basic
OOPS do the work!
Collapse | Copy Code
Kelvin *mainComponent = new Kelvin();

KelvinDecorator *pAddedFunctionality = new SpacemanDecorator(
new DinoDecorator (
new TracerBazookaDecorator(mainComponent) ) );

pAddedFunctionality->MisBehave();
Weve done nothing but add one layer of Kelvin on top of another. KelvinDecorator does its
job and hands the baton to another KelvinDecorator, which in turn hands it to another, and
so on and so forth. And, we did all this without modifying the main component class Kelvin!

Congratulations, youve just learnt another design principle: Open-Close principle. Which simply
means a class should be closed for modification, but open for extension or change.
For our example, the class Kelvin is closed for modification we never had to modify the
Kelvin class. But we still were able to alter Kelvins behavior through decorators (thus we
made it open for extension).
And we did this by adding new layers of KelvinDecorator at run-time!
And last but not least, the output of our program:

Things work great. Now it is easy to add and combine any of Kelvins behaviors with very little
design change, and more importantly, all this with no change in the Kelvin class!
Change in Requirement
Let's see how easy Decorator makes it for handling change\adding new behavior.
Kartoon Kompany wants a new behavior for Kelvin for next weeks comic strip: an episode with
Susie.
Our design now makes it very easy to add new behavior. If you need a new
WithSusieDecorator, just add the new subclass decorator (write a WithSusieDecorator and
derive it from KelvinDecorator) to get the desired functionality. In fact, do try doing this as an
assignment to see how easy it is to add a new decorator with very little change to the existing
design and code. Try outputting the text GROSS! Let's hit Susie D with 1,000 snowballs!!
You also need to create a new WithSusieDecorator() when creating layers of Kelvin
Decorators in our client function (you could use a Factory for this, but that is a different design
pattern for a different day!).
Thats it! How easily we have added new behavior at runtime. Can you imagine the pain and
amount of changes to make if we still had used the static-subclassing way?
Kartoon Kompany is screaming with pleasure at how easy and resilient our new design is to
change!
Theyre so happy that they plan to introduce you in next weeks strip and let Kelvin hit you with
1,000 snowballs!
A change like that is now easy and systematic, thanks to the Decorator Design Pattern, but
whether you want to put up with Kelvins antics is up to you!
Decorator Design Pattern Considerations
Okay, now that youve understood the Decorator Design Pattern, there are a few more things you
should be aware of:
1. Dont derive KelvinDecorator directly from Kelvin. You should take out the common,
required interfaces and put them as a base class (Character?), and have Kelvin derive from the
Character superclass. KelvinDecorator also derives from the Character superclass. This
makes the decorator light-weight, and doesnt hog it with all unnecessary functionality from
Kelvins class.
2. While decorators are great, they have their disadvantages:
o It's very difficult for a developer who doesnt know this pattern to understand a code written with
decorators. You are better than that poor dude as you now know about decorators!
o Decorators tend to add a lot of small classes, but thats something you have to live with.
o Any client code that relies on RTTI (i.e., if the client checks for a derived class object type, or in
simpler words, whether this is a Kelvin object) won't work for decorators. This is because you do
not know which decorator layer object we have with us. It could be Spaceman, TRex, Tracer.
3. Go read the Decorator Design Pattern from GoF book now! This article was intended to make
things easy to understand, and to whet your appetite for the GoF chapter on decorators. Search
for "Design Patterns: Elements of Reusable Object-Oriented Software", or the GoF book as it is
affectionately called.
License

Applying Observer Pattern in C++
Applications
Introduction
Many hands make work light, likewise many objects join hands in the development of complex
systems. The rule of thumb in Object Oriented Design is to decompose the system into set of
cooperating objects. Each decomposed object must be complete and it should express high
degree of cohesion and have low degree of coupling with other objects. High degree of
cohesiveness means that the object is self-contained and low degree of coupling means it is not
too much dependent on other objects. However, in the world of objects, each object should
interact with the fellow objects to provide the complete solution. This article explains how to
avoid object dependencies using the Observer Pattern with a simple example. It also talks about
when and why the Observer Pattern is needed, its benefits and liabilities.
Design Patterns are meant to provide a common vocabulary for communicating design
principles. The Observer Pattern is classified under Object Behavioral Patterns in the book,
Design Patterns: Elements of Reusable Object-Oriented Software by Erich Gamma et al.
(Addison-Wesley, 1995). In this article, I will be using the terms used by 'Gang of Four (GoF)' to
explain Observer Pattern. First, let us understand the problem of object interaction.
Problem
An object has an internal state and provides a set of services. Usually, services are implemented
as methods and data members determine the state of the object. Let us take an example of
interaction between two objects. Object 'A' needs to maintain a reference to Object 'B' directly or
indirectly to use its services. In languages like C++, Object 'A' should include the header file
containing the class definition of Object 'B'. This is fine when the classes of Objects 'A' and 'B'
belong to the same abstraction, so that they are always reused together. However, when the
classes are unrelated, they are totally independent and can be used in two different contexts in
two different applications. Including 'B's' header file in Object 'A' makes it impossible to reuse 'A'
without 'B'.
Sometimes, the state of the object 'A' may depend on the state of object 'B'. Whenever 'B'
changes, 'A' should recompute its state to remain in Sync with 'B'. The situation becomes more
complicated when a new Object 'C', which is dependent on the state of 'B' is brought into the
application. In short, the dependency and the coupling between the objects are increased and
the reusability is reduced. How can we make two or more independent objects work together
without knowing each others existence? The answer is The Observer Pattern.
The Observer Pattern
GoF classifies the Observer Pattern as an Object Behavioral Pattern. The Observer Pattern is
intended to "Define a one-to-many dependency between objects so that when one object changes
state, all its dependents are notified and updated automatically". An object that is subjected to
change is called a Subject and an object that depends on the Subject's state is called an
Observer. In the above example, 'B' can be a Subject and Objects A and C can be Observers. A
Subject can have any number of Observers. When the Subject changes its state, it Notifies all
the Observers and the Observers query the Subject to maintain state consistency with the
Subject.
UML Class Diagram and Participants
Participants of the Observer Pattern is shown in the UML class diagram. Subject maintains a list
of Observers and provides interface for attaching and detaching them. Observer defines an
abstract Update interface, which is called by the Subject when its state changes. Concrete Subject
maintains state of interest for Concrete Observers and notifies them when the state changes.
Concrete Observer implements the update interface provided by the Observer. It also maintains
a reference to Concrete Subject and updates its state to be in sync with the Concrete Subject.

Example
This article uses Stair-Master as an example to explain the concept of the Observer Pattern. Stair-
Master is a fitness equipment mainly intended for Cardiovascular exercises. It simulates the effect
of climbing stairs and offers different kinds of fitness programs including Fatburn, Cardio,
Random and Hill. The person using the Stair-Master must specify the workout duration, age,
effort level and the workout program. It contains a set of monitors that are used to control and
visually indicate the progress of the workout. Time monitor keeps track of the elapsed workout
time and is responsible for stopping the workout after the specified duration. Heart rate monitor
reads the current heart rate and indicates it with respect to low and high values for the current
workout program. Program controller can be used to change the workout program and effort
level at any time during the workout. Calorie monitor displays total calories burned and average
caloric burn per minute.
Target heart rate for a person is calculated based on the age and the workout program selected.
Normally, Fatburn programs have lower heart rates when compared with Cardio programs. Time
monitor interacts with the Heart rate monitor to read heart rate every second and with the
Calorie monitor to update the total calories burnt. When the workout program changes, the
Program controller informs the Heart rate monitor to recompute the target heart rate.
Time monitor, Heart rate monitor, Program controller and Calorie monitor can be modelled as
independent objects, so that they can be used in the design of any Cardio equipment. Some
Stair-Masters can have Distance monitors to show the total floors climbed and the total distance
covered in meters. Also, advanced machines can use a Heart rate variation monitor instead of a
Heart rate monitor to indicate the variation in the heart rate over a period of time.
Following dependency graph shows the dependency between various objects used in this
example.

Direct Object Interaction
First, let us see what are the problems in having direct interactions between independent objects.
If the objects are directly interacting with each other, they have to hold a pointer or the reference
to the dependent object. This makes it difficult to
i) Add a new dependent object
ii) Replace an existing dependent object with a new object
iii) Remove an existing dependent object.
i) Adding a new dependent object
In the next version, if the Distance monitor is added to the Stair-Master, the dependency is
further increased and the Time monitor should be changed to maintain a reference to the
Distance monitor. The refined dependency graph is shown below

ii) Replacing an existing dependent object with a new object
When a Heart rate variation monitor replaces the Heart rate monitor, the Time monitor and the
Program controller needs to be changed (See above diagram for object dependencies).
iii) Removing an existing dependent object
It is not necessary for a Cardiovascular equipment to have all the above mentioned monitors.
Some Elliptical cross trainers don't have a Heart rate monitor. Since Time monitor and Program
controller maintains direct references to Heart rate monitor, they cannot work without Heart rate
monitor. This makes it impossible to remove Heart rate monitor, even if it is not needed.
Using Observer Pattern
Observer Pattern can be used to address all the above mentioned problems. Time monitor, Heart
rate monitor, Calorie monitor and Program controller can be treated as Observers and a new
object Cardio Subject can be introduced to act as a Subject. These monitors will not know the
existence of each other and they always communicate through the Cardio Subject. When one of
the monitors changes its state (say Time Monitor), it updates the Cardio Subject, which in turn
notifies all the monitors. In response to the notification, the monitors query the Cardio Subject to
update their states. Since the monitors are independent of each other, a new monitor can be
easily added, an existing monitor can be removed or replaced with a new one. Observer Pattern
is demonstrated using a complete Visual C++ Stair-Master application.
Change propagation mechanisms
When the state of the Subject is changed, the Observers must have their states changed. This
section contains two change propagation mechanisms, Notification and Polling, which can be
used to maintain state consistency between the Subject and Observers.
Notification
When there is change in Subjects state, its Observers are notified by calling the Notify method.
In response to the notification, the Observers query the required data from the Subject to
maintain state consistency. Observers can even register for specific events of interest and in the
occurrence of such an event, the Subject can send notifications only to the interested Observers.
Maintaining self-consistency of the Subject and avoiding redundant notifications are two
important issues that should be considered in the Notification process.
Maintaining self consistency of the Subject
Self-consistency is all about retaining state of the Subject after notifying the Observers. It is
important to make sure that the Subjects state is self-consistent before and after calling Notify
method to keep the state of Observers in sync with the Subject. It is difficult to maintain self-
consistency in inherited operations, that too, when Notify method is called in the base class. A
simple example is shown in Listing 1.
In this example, CDervSubject overrides the operation Calculate and calls the base class method,
which sends the notification to all the Observers. The derived class implementation can change
the value of the data member m_nResult, bringing in the problem of self-inconsistency. To avoid
this, GoF suggests the use of Template methods. Primitive operations can be defined as
protected virtual methods that can be overridden by the derived classes and call the Notify
method as the last operation in the template method to maintain self-consistency. Listing 2
illustrates this.
Avoiding redundant notifications
Sometimes, calling Notify method in each and every state changing method is not necessary. A
single Notify call after all the state changes will avoid redundant notification calls. In Listing 3, the
Observer receives three notification calls instead of one. This can be achieved by using a Change
Tracker class that has a set of Change Tracking methods (see Listing 4). To ensure a single
notification call at the end of all state changes, CMySubject should inherit from CChangeTracker
and implement the methods. Instead of calling Notify method in all state changing methods,
CMySubject calls StartChange before making the change and FinishChange after making the
change. A change reference count is incremented during StartChange and decremented during
FinishChange and Notify method is called only when the reference count reaches 0. The
advantage of this approach is any number of state changing methods can be called in any
sequence and the Observers will be notified only once at the end of all the state changes. Listing
4 illustrates this.
Advantages
1. Simple and straightforward implementation in most cases.
2. Change in the state of the Subject is immediately propagated to all the Observers.
Disadvantages
1. Subject can be reused only with the Observer abstraction. This reduces the reusability of the
Subject in a totally different context.
2. Subject should maintain a list of Observers. In some cases, the Observers may request only for
specific events for which the Subject has to notify them. Subject should also maintain this
information along with the list of Observers, which increases the overhead.
3. Since Observers are independent of each other, changing Subjects state in the Update method
of an Observer without a well-defined dependency criterion should not be encouraged. Doing so
may result in
i) Recursive notification calls.
ii) Inconsistent Observer states, that is each Observer will be in different states at
the same time.
Polling
In this approach, the Observer polls the Subject for state changes. When the Subject changes,
the Observer is not notified with the change, but the Observer uses a polling algorithm to read
the state change from the Subject. Polling is widely used in popular class libraries. MFC uses the
polling technique to update user-interface objects. See Polling in MFC for more details.
Advantages
1. The Subject is totally unaware of Observers. It need not maintain the list of Observers and notify
them about the state changes.
2. Observers take the responsibility of maintaining the state consistency. This increases the
reusability of the Subject.
Disadvantages
1. When to poll the Subject. Subject should be polled at the right time, if the Subject is polled too
early, the Observers will have old state and if the poll is too late, they lose the intermittent states.
2. Performance overhead is introduced when polling a Subject, which has not changed.
3. Somebody should ask the Observers to poll the Subject. Who notifies the Observer do this can
be very big question?
Object Interaction Models
The Subject and the Observers can interact using a Push Model or a Pull Model.
Push Model
In this model, the Subject pushes the state changes to the Observers. Push model can be used
when all the Observers are interested in common state changes. Observers have no choice other
than receiving the pushed data. Push model cannot be used with large amount of data, as an
Observer may not be interested in all the data that is being pushed. Also, the Subject must know
something about the Observer to which it is pushing the data. Therefore, the Observers have to
comply with a standard interface required by the Subject and the Subjects reusability is limited
to these Observers.
Pull Model
In this model, the Subject notifies the state change to the Observers and the Observers pull only
the required data from the Subject. Pull model is more flexible and the Observers can pull only
the required data. But, more than one method call is required to implement the pull model. The
first method call is for change notification from the Subject to all its Observers and an interested
Observer must call at least one more method to pull the data. In a very dynamic environment,
the state of the Subject can change between these two calls, that is before the Observer pulls the
data. Therefore, the Subject and the Observers may not be in sync. Above all, the Observers call
specific methods to pull the required data and it is up to them to figure out what is changed
without getting much help from the Subject. Sample application presented with this article uses
the Pull Model.
Benefits
1. The Observer Pattern avoids direct object interactions and can be used when one or more
objects are interested in the state changes of a given object.
2. It can be used to develop loosely coupled applications maintaining object state dependencies.
3. It can be used when the number of state dependent objects is not known in advance or even
when the number may even change over time.
4. Subject and the Observer objects can be reused separately and they can vary independently.
5. The Observer Pattern can be used to develop application in layers. For example, a user interface
application can contain spreadsheet, graph, and chart objects (Observers, at a higher level) that
are dependent on the data from a database object (Subject, at a lower level). When the data in
the database object changes all the Observers are automatically notified through the abstract
operation defined in the Observer base class. Since the abstract operation is defined in the base
class, the Subject need not know the concrete Observer classes and hence they are loosely
coupled.
6. Since all the Observers are notified through the same abstract operation, it is easy to add or
remove Observers on demand.
Liabilities
1. In most situations, Observers will simply be only notified about a state change. It is up to the
Observer to find out what exactly has changed. However, this can be avoided by including
additional information (or the Aspect of change) along with the notification. This will give some
clue about the change to the Observer.
2. Observer objects are totally independent and they have no knowledge on the existence of the
fellow Observers. Therefore, an Observer object can change the state of the Subject (in the
Update method) before even all the Observers are notified. This may result in state
inconsistencies and the state change notifications will be lost.
3. Whenever an Observer changes the Subjects state, all the dependent Observers are notified. If
the dependency criteria is not well defined, recursive updates can easily happen. Usually, in Stair-
Masters the workout program and the heart rate are mutually dependent. That is, when the
program changes (say from Fat Burn to Cardio) the heart rate changes and when the heart rate
range falls below or goes above a threshold limit the program automatically changes. For the
sake of simplicity, this dependency criterion is not enforced in the example. Assuming that the
dependency criterion is not well defined in the example, Program controller will update the
Cardio Subject when the program changes and Heart rate monitor will recompute the heart rate.
If the heart rate falls below or goes above the threshold level, the heart rate monitor will update
the Cardio Subject to change the program, which in turn will update the Program controller and
this cycle repeats. Therefore, Heart rate monitor and Program controller blindly updates the
Cardio Subject, which notifies both these monitors to update themselves resulting in recursive
update calls.
4. Observer Pattern introduces an additional level of indirection to maintain state consistency. This
increases the flexibility in the application design, but has a sure performance impact. Also, too
many indirections decrease the understandability of the code.
5. When the Subject is deleted, the Observers dont have a direct way to know about the deletion.
Therefore, the Observers will have dangling reference to the deleted Subjects.
Known Uses
This section presents known uses of the Observer Pattern. Some of the known uses presented in
this section are taken from the GoF book on Design Patterns.
Polling in MFC
Observers should poll the Subject at the right time to get its state. In a MFC application, the
user-interface objects such as menu items and toolbar buttons are Observers and the document,
view, window or application object is the Subject. MFC uses the polling technique to update
these user-interface objects (Observers). Before a menu drops down or during the idle loop in
the case of toolbar buttons, MFC routes an update command. The handler for the update
command (defined using ON_UPDATE_COMMAND_UI) is called in the right object to
enable/disable the menu item or the toolbar button. Using polling in this case is advantageous
because of the following reasons:
1. MFC can defer updating the user-interface objects till the occurrence of a specific event.
Therefore, toolbar states can be updated when the application is idle and menu items can be
updated when the menu drops down.
2. Menu item or the toolbar button state purely depends on the current state of the Subject (state
contained in document, view, window or application) and not its old state. Therefore, the user-
interface objects need not update their states for every state change in the Subject.
MFC's Document/View Architecture
MFC's Document/View architecture uses the Observer Pattern. A document contains the data
object and acts as a Subject. A view is a window object through which the user updates the
document and it acts as an Observer. A document can have multiple views. Whenever the data in
the document is changed by one of the views, it updates the document by calling
UpdateAllViews method, with optional hint about the modification. To inform about the change
to other views, the document object calls OnUpdate method for each view attached to it (except
the view that called UpdateAllViews). Derived view classes can override the OnUpdate method
and update themselves by querying the data from the document.
Model/View/Controller in Smalltalk
The first and perhaps the best-known example of the Observer Pattern appears in Smalltalk
Model/View/Controller (MVC), the user interface framework in the Smalltalk environment. MVC's
model class plays the role of Subject, while View is the base class for Observers.
Observer and Publish/Subscribe
Due to the object interaction, the Observer Pattern is also referred as Publish/Subscribe.
Observers subscribe to the Subject for change notifications and in-turn the Subject publish the
state changes to the subscribed Observers. Publish/Subscribe (also called as
Publisher/Subscriber) can be viewed as a variant of the Observer Pattern. Even though, the intent
of both these Patterns is same, Publisher/Subscriber tries to address some of the implementation
limitations of the Observer Pattern.
Summary
Many objects work in unison behind a complex object oriented application. Handling the state
dependencies between these objects is a major task. This article showed how the Observer
Pattern could be used to maintain state consistencies. It started with a common programming
problem, then it explained what, when and why the Observer Pattern is needed with a simple
example. Benefits, liabilities, and known uses of the Pattern is also presented. The Observer
Pattern can help to maintain the state consistencies between objects, and enhance the
correctness and the quality of the system. However, it is not the silver bullet for solving all object
interaction problems.
Acknowledgments
Special thanks to my friend Sree Meenakshi for her helpful suggestions in improving the clarity
and presentation of this article.
Listing 1 - Self consistency violation in the
Subject
Collapse | Copy Code
INT CDervSubject::Calculate( int nVal )
{
// Call the base class method, which implements a complicated <BR> // calculation
algorithm and sets the data member m_nResult
CBaseSubject::Calculate( nVal ); // Calling this method sends a <BR>
// notification to the Observers
// Specific implementation for the derived class
if( m_nResult > 1000 )
{
m_nResult %= 1000;
}
return 0;
}
Listing 2 - Using Template method to
maintaining self consistency of the Subject
Collapse | Copy Code
INT CBaseSubject::Calculate( int nVal )
{
// Call DoCalculate that can be redefined in derived classes.
// DoCalculate is a protected virtual method
DoCalculate( nVal );
// Notify the Observers about the change
Notify();
return 0;
}
INT CBaseSubject::DoCalculate( int nVal )
{
// Do calculation and set m_nResult
return 0;
}
INT CDervSubject::DoCalculate( int nVal )
{
// Call base class method
CBaseSubject::DoCalculate( nVal );
// Specific implementation for the derived class
if( m_nResult > 1000 )
{
m_nResult %= 1000;
}
return 0;
}
Listing 3 - Redundant notifications
Collapse | Copy Code
void CMySubject::SetFont( Font & rFont )
{
...
...
// Update member
m_Font = rFont;
...
...
// Notify the Observers
Notify();
}

void CMySubject::SetTextColor( Color & rTextColor )
{
...
...
// Update member
m_TextColor = rTextColor;
...
...
// Notify the Observers
Notify();
}

void CMySubject::SetBkColor( Color & rBkColor )
{
...
...
// Update member
m_BkColor = rBkColor;
...
...
// Notify the Observers
Notify();
}

void CMySubject::SetAttributes( Font & rFont, Color & rTextColor, <BR>
Color & rBkColor )
{
// Call SetFont method
SetFont( rFont );
// Call SetTextColor method
SetTextColor( rTextColor );
// Call SetBkColor method
SetBkColor( rTextColor );
}

// Observer code
void CMyObserver::SetAttributes()
{
...
...
m_MySubject.SetAttributes( Font, TextColor, BkColor );
...
...
}
Listing 4 - Notification using Change Tracker
Collapse | Copy Code
class CChangeTracker
{
protected :
virtual void StartChange() = 0 ;
virtual void FinishChange() = 0;
};

// CMySubject inherits from CSubject and CChangeTracker
class CMySubject : public CSubject, protected CChangeTracker
{
protected :
virtual void StartChange();
virtual void FinishChange();
private :
INT m_nChangeCount;
};

void CMySubject::StartChange()
{
m_nChangeCount++;
}

void CMySubject::FinishChange()
{
m_nChangeCount--;
if( m_nChangeCount == 0 )
{
Notify();
}
}

// State change operations
void CMySubject::SetFont( Font & rFont )
{
// call StartChange
StartChange();
...
...
// Update member
m_Font = rFont;
...
...
// call EndChange
EndChange();
}

void CMySubject::SetTextColor( Color & rTextColor )
{
// call StartChange
StartChange();
...
...
// Update member
m_TextColor = rTextColor;
...
...
// call EndChange
EndChange();
}

void CMySubject::SetBkColor( Color & rBkColor )
{
// call StartChange
StartChange();
...
...
// Update member
m_BkColor = rBkColor;
...
...
// call EndChange
EndChange();
}

void CMySubject::SetAttributes( Font & rFont, Color & rTextColor, <BR>
Color & rBkColor )
{
// call StartChange
StartChange();
// call SetFont method
SetFont( rFont );
// call SetTextColor method
SetTextColor( rTextColor );
// call SetBkColor method
SetBkColor( rTextColor );
// call EndChange
EndChange();
}

Factory Method Pattern vs. Abstract Factory
Pattern
Introduction
Design patterns are reusable and documented solutions for commonly occurring problems in
software programming or development.
In one of my previous article about Factory Pattern I spoke about what are different flavors of
Factory pattern and how to choose between them. But I think there are some confusion with
regards to Factory Method Pattern and Abstract Factory. So we will work on it.
Who should read this article?
If you have confusion understanding the difference between Factory Method Pattern and
Abstract Factory Pattern you are at right place.
What these two are?
First of all both of them falls under Creational category and it means it will
solves the problem pertaining to object creation.
Factory Method and abstract factory pattern all are about creating
objects.

In this article I would like to emphasize on one more terminology that is Simple Factory.
1. Simple Factory and Factory Method
For our discussion lets have a small problem statement.

Class structure
Collapse | Copy Code
public interface ICustomer
{
void AddPoints();
void AddDiscount();
}

public class GoldCustomer : ICustomer
{
public void AddPoints()
{
Console.WriteLine("Gold Customer - Points Added");
}

public void AddDiscount()
{
Console.WriteLine("Gold Customer - Discount Added");
}

public void GoldOperation()
{
Console.WriteLine("Operation specific to Gold Customer");
}
}

public class SilverCustomer : ICustomer
{
public void AddPoints()
{
Console.WriteLine("Silver Customer - Points Added");
}

public void AddDiscount()
{
Console.WriteLine("Silver Customer - Discount Added");
}

public void SilverOperation()
{
Console.WriteLine("Operation specific to Silver Customer");
}
}
Problem Statement
Client want to create Customer Object (either Gold or Silverbased on requirement).
Simple Factory
This is one of the pattern not born from GOF and most of the peopleconsiders this as the default
Factory method pattern.
Here, we will just take out object creation process out of the client code and put into some other
class. Look at the code demonstration.
Collapse | Copy Code
class CustomerFactory
{
public static ICustomer GetCustomer(int i)
{
switch (i)
{
case 1:
GoldCustomer goldCustomer = new GoldCustomer();
goldCustomer.GoldOperation();
goldCustomer.AddPoints();
goldCustomer.AddDiscount();
return goldCustomer;
case 2:
SilverCustomer silverCustomer = new SilverCustomer();
silverCustomer.SilverOperation();
silverCustomer.AddPoints();
silverCustomer.AddDiscount();
return silverCustomer;
default: return null;
}
}
}

//Client Code
ICustomer c = CustomerFactory.GetCustomer(someIntegerValue);
Factory Method Pattern
In this pattern we define an interface which will expose a method which will create objects for us.
Return type of that method is never be a concrete type rather it will be some interface (or may be
an abstract class)
Collapse | Copy Code
public abstract class BaseCustomerFactory
{
public ICustomer GetCustomer()
{
ICustomer myCust = this.CreateCustomer();
myCust.AddPoints();
myCust.AddDiscount();
return myCust;
}
public abstract ICustomer CreateCustomer();
}

public class GoldCustomerFactory : BaseCustomerFactory
{
public override ICustomer CreateCustomer()
{
GoldCustomer objCust = new GoldCustomer();
objCust.GoldOperation();
return objCust;
}
}
public class SilverCustomerFactory : BaseCustomerFactory
{
public override ICustomer CreateCustomer()
{
SilverCustomer objCust = new SilverCustomer();
objCust.SilverOperation();
return objCust;
}
}
//Client Code
BaseCustomerFactory c = new GoldCustomerFactory();// Or new SilverCustomerFactory();
ICustomer objCust = c.GetCustomer();
Note:- To understand when to use Simple Factory and when to use Factory Method Pattern
click here.
2. Abstract Factory Pattern
In Abstract Factory we define an interface which will create families of related or dependent
objects. In simple words, interface will expose multiple methods each of which will create some
object. Again, here method return types will be generic interfaces. All this objects will together
become the part of some important functionality.
Question If every factory is going to create multiple objects and all those objects will be related
to each other (means they will use each other) how this relating happens and who does that?
Answer
There will be an intermediary class which will have composition relationship with our interface.
This class will do all the work, using all the objects got from interface methods.
This will be the class with which client will interact.
Lets talk about a scenario.
We want to build desktop machine. Let see what will be the best design for that,
Collapse | Copy Code
public interface IProcessor
{
void PerformOperation();
}
public interface IHardDisk { void StoreData(); }
public interface IMonitor { void DisplayPicture();}

public class ExpensiveProcessor : IProcessor
{
public void PerformOperation()
{
Console.WriteLine("Operation will perform quickly");
}
}
public class CheapProcessor : IProcessor
{
public void PerformOperation()
{
Console.WriteLine("Operation will perform Slowly");
}
}

public class ExpensiveHDD : IHardDisk
{
public void StoreData()
{
Console.WriteLine("Data will take less time to store");
}
}
public class CheapHDD : IHardDisk
{
public void StoreData()
{
Console.WriteLine("Data will take more time to store");
}
}

public class HighResolutionMonitor : IMonitor
{
public void DisplayPicture()
{
Console.WriteLine("Picture quality is Best");
}
}
public class LowResolutionMonitor : IMonitor
{
public void DisplayPicture()
{
Console.WriteLine("Picture quality is Average");
}
}
Factory Code will be as follows
Collapse | Copy Code
public interface IMachineFactory
{
IProcessor GetRam();
IHardDisk GetHardDisk();
IMonitor GetMonitor();
}

public class HighBudgetMachine : IMachineFactory
{
public IProcessor GetRam() { return new ExpensiveProcessor(); }
public IHardDisk GetHardDisk() { return new ExpensiveHDD(); }
public IMonitor GetMonitor() { return new HighResolutionMonitor(); }
}
public class LowBudgetMachine : IMachineFactory
{
public IProcessor GetRam() { return new CheapProcessor(); }
public IHardDisk GetHardDisk() { return new CheapHDD(); }
public IMonitor GetMonitor() { return new LowResolutionMonitor(); }
}
//Let's say in future...Ram in the LowBudgetMachine is decided to upgrade then
//first make GetRam in LowBudgetMachine Virtual and create new class as follows

public class AverageBudgetMachine : LowBudgetMachine
{
public override IProcessor GetRam()
{
return new ExpensiveProcessor();
}
}
Collapse | Copy Code
public class ComputerShop
{
IMachineFactory category;
public ComputerShop(IMachineFactory _category)
{
category = _category;
}
public void AssembleMachine()
{
IProcessor processor = category.GetRam();
IHardDisk hdd = category.GetHardDisk();
IMonitor monitor = category.GetMonitor();
//use all three and create machine

processor.PerformOperation();
hdd.StoreData();
monitor.DisplayPicture();
}
}
Collapse | Copy Code
//Client Code
IMachineFactory factory = new HighBudgetMachine();// Or new LowBudgetMachine();
ComputerShop shop = new ComputerShop(factory);
shop.AssembleMachine();
Conclusion

Applying Strategy Pattern in C++
Applications
Introduction
Software consulting companies do projects for their customers on a "Fixed Price basis" or on a
"Time and Material basis". Also, the projects can be either onsite or offsite. Usually, the customers
specify how they want the project to be done (Fixed price or Time and Material basis, onsite or
offsite). The ultimate aim of the consulting company is to complete the project in the scheduled
time, however the Strategy (or the policy) they adapt in doing the project may differ, depending
on how they do the project. This is a real life example, where a Strategy Pattern is applied.
Strategy Pattern can also be used in the software design. When it is possible to have several
different algorithms for performing a process, each of which is the best solution depending on
the situation, then a Strategy Pattern can be used. This article is all about Strategy Pattern. It
uses a programming example to explain what, when and why a Strategy Pattern is needed.
Benefits and drawbacks of using Strategy Pattern in software design is discussed. Three different
approaches for implementing the Pattern in C++ and known uses of Strategy Pattern are also
presented in this article.
Design Patterns are meant to provide a common vocabulary for communicating design
principles. Strategy Pattern is classified under Behavioral Patterns in the book, Design Patterns:
Elements of Reusable Object-Oriented Software by Erich Gamma et al. (Addison-Wesley,
1995). In this article, I will be using the terms used by 'Gang of Four (GoF)' to explain Strategy
Pattern.
An Example
A progress indicator is a window that an application can use to indicate the progress of a lengthy
operation (for example, an Installation Process). It is usually a rectangular window that is
gradually filled, from left to right, with the highlight color as the operation progresses. It has a
range and a current position. The range represents the entire duration of the operation, and the
current position represents the progress the application has made towards completing the
operation. The range and the current position are used to determine the percentage of the
progress indicator to fill with the highlight color.
Even though left to right direction is commonly used for filling in most progress indicators, other
directions like right to left, top to bottom and bottom to top can also be used for filling. I have
seen some progress indicators using a bottom to top filling. Also, different types of fills like
continuous fill, broken fill or pattern based fills can be used with a given filling direction.
In short, the purpose of the progress indicator remains unchanged; however, the filling direction
or the filling algorithm can change. Therefore, the family of algorithms used for filling can be
encapsulated in a separate filler class hierarchy and the application can configure the progress
indicator with a concrete filler class. An algorithm that is encapsulated in this way is called a
Strategy. So, what is a Strategy Pattern? The Strategy Pattern is a design pattern to encapsulate
the variants (algorithms) and swap them strategically to alter system behavior without changing
its architecture. According to GoF, Strategy Pattern is intended to, Define a family of algorithms,
encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary
independently from clients that use it.
Strategy Pattern has three participants that include Strategy, Concrete Strategy and Context. In
this example, the abstract filler class CFiller, is referred as the Strategy, the concrete filler classes
CLToRFiller (for providing Left to Right fill) and CRToLFiller (for providing Right to Left fill) are
referred as Concrete Strategies and the progress indicator CProgressIndicator, is referred as the
Context using Strategy. The application using the progress indicator is the client for the Context.
Depending on the situation, the client specifies the progress indicator (Context) with a concrete
filler class object (Concrete Strategy).
CProgressIndicator maintains a reference to the CFiller object. Whenever there is a progress in
the operation, the application notifies CProgressIndicator (by calling a method like SetPos); the
CProgressIndicator forwards the request to the CFiller object to visually indicate the change.
CFiller subclasses, CLToRFiller and CRToLFiller implement the filling algorithm (in DoFill method).
By isolating the filling algorithm from the progress indicator, new filling strategies can be used
without changing the progress indicator. Encapsulating the filling algorithm separately eliminates
the need for multiple conditional statements to choose the right Strategy for filling. UML
diagram showing the relationship between the participants of the Strategy Pattern is presented
below.

Approaches for implementing Strategy
Pattern in C++
Push and Pull methods can be used to provide a means of safe data exchange and reduce the
coupling between the Context and Strategy objects. In the Push method, the Context pushes the
data to the Strategy object and the Strategy uses the data to implement the algorithm. In this
method, Context might pass some unwanted data to the Strategy object, as all Concrete
Strategy objects might not require all the data. On the other hand, in the Pull method, the
Context, registers itself with the Strategy which in-turn maintains a reference to the Context
object and pulls the required data from it. In this method, the Context must define an elaborate
set of Get methods for the Strategy objects to pull the required data. Since, the Strategy
maintains a reference to the Context, both the classes are tightly coupled. The choice of Push or
Pull method purely depends on the requirement.
This article discusses three different approaches for implementing the Strategy Pattern in C++.
The approaches described below can use either a Push or Pull method.
Strategy object as a required parameter to the Context
Strategy object as an optional parameter to the Context
Strategy as a template class parameter to the Context
Strategy object as a required parameter to
the context
In this approach, the progress indicator (Context) takes a filler (Strategy) object as a parameter in
its constructor and maintains a reference to it. The progress indicator delegates the request to
the filler object when SetPos method is called. Listing 1 shows this approach. Also, Layout
Manager in Java uses this approach, see Java and Strategy Pattern for explanation.
Advantage
1. The progress indicator depends only on the interface of the filler class and does not interact
directly with the concrete subclasses of the filler class.
2. Application can select the required filler class object at run-time. SetFiller method can be used to
change the filler class object after creating the progress indicator.
Disadvantage
1. Application using the progress indicator must be aware of all the filler classes and must supply
the progress indicator with the required filler class object.
2. Progress indicator is not having any control on the scope or the lifetime of the filler class object.
Strategy object as an optional parameter to
the Context
This approach is similar to the first approach, but the filler object (Strategy) is taken as an
optional parameter when progress indicator (Context) is created. The progress indicator creates a
default filler object (Left to Right filler), if the application did not specify the filler object during
construction. Listing 2 contains C++ sample showing this approach. Demo application provided
with this article uses this technique.
Advantage
1. Application can specify the filler object only when it needs to change the default filler object.
2. Application can select the required filler class object at run-time. SetFiller method can be used to
change the filler class object after creating the progress indicator.
Disadvantage
1. Progress indicator must be aware of the concrete filler class CLToRFiller, for providing the default
behavior. This increases the coupling between the CProgressIndiator and CLToRFiller classes.
2. Progress indicator has control only on the lifetime of the default filler object, which is CLToRFiller
object in this case. But, it is not having any control on the scope or the lifetime of other filler class
objects.
Strategy as a template class parameter to
the Context
If there is no need to change the filler class (Strategy) at run time, it can be passed as a template
parameter to the progress indicator (Context) class at compile time. Listing 3 shows this
approach. Active Template Library (ATL) uses a variation of this approach to select the required
CCOMObjectxxx<> in which the Context is passed as a parameter to the Strategy class (Pull
method). See ATL and Strategy Pattern for explanation.
Advantage
1. Progress indicator template class is instantiated only with concrete filler classes, so there is no
need for the abstract CFiller class.
2. Passing filler class as a template parameter provides an early binding between the progress
indicator and the filler classes. This avoids runtime overhead and increases the efficiency.
3. Progress indicator is responsible for the creation of the filler class object. Therefore, it has full
control on the lifetime of the object.
Disadvantage
Selecting filler class at compile time provides no room for changing the object at runtime.
Benefits in using Strategy Pattern
1. A family of algorithms can be defined as a class hierarchy and can be used interchangeably to
alter application behavior without changing its architecture.
2. By encapsulating the algorithm separately, new algorithms complying with the same interface
can be easily introduced.
3. The application can switch strategies at run-time.
4. Strategy enables the clients to choose the required algorithm, without using a "switch"
statement or a series of "if-else" statements.
5. Data structures used for implementing the algorithm is completely encapsulated in Strategy
classes. Therefore, the implementation of an algorithm can be changed without affecting the
Context class.
6. Strategy Pattern can be used instead of sub-classing the Context class. Inheritance hardwires the
behavior with the Context and the behavior cannot be changed dynamically.
7. The same Strategy object can be strategically shared between different Context objects.
However, the shared Strategy object should not maintain states across invocations.
Drawbacks in using Strategy Pattern
1. The application must be aware of all the strategies to select the right one for the right situation.
2. Strategy and Context classes may be tightly coupled. The Context must supply the relevant data
to the Strategy for implementing the algorithm and sometimes, all the data passed by the
Context may not be relevant to all the Concrete Strategies.
3. Context and the Strategy classes normally communicate through the interface specified by the
abstract Strategy base class. Strategy base class must expose interface for all the required
behaviors, which some concrete Strategy classes might not implement.
4. In most cases, the application configures the Context with the required Strategy object.
Therefore, the application needs to create and maintain two objects in place of one.
5. Since, the Strategy object is created by the application in most cases; the Context has no control
on lifetime of the Strategy object. However, the Context can make a local copy of the Strategy
object. But, this increases the memory requirement and has a sure performance impact.
Known Uses
This section presents known uses of Strategy Pattern. Some of the known uses presented in this
section are taken from the GoF book on Design Patterns.
ATL and Strategy Pattern
ATL stands for Active Template Library. It is a collection of template based classes intended to
hide most of the complexities behind COM development and provide a small footprint for the
component itself.
In ATL, the class of the COM object is not instantiated directly. It acts as a base class for a
CComObjectxxx<> class. For example, if CMyClass is the COM object class, then the most
derived class in the class hierarchy will be a CComObjectxxx<CMyClass>. CComObjectxxx<>
provides the implementation of IUnknown methods. However, these classes not only handle the
basics of reference counting, but also interact appropriately with the lock count of the module.
CComObjectxxx<> classes differ slightly in their behavior and the choice of the
CComObjectxxx<> depends on the aggregation, locking and destruction models. These are
generic and optional features that can be applied to any COM object. For example, some COM
Objects can support aggregation, some may not and some may only support aggregation. This is
again true with the other two features - locking and destruction. These features can be
accommodated and easily switched around without changing the functionality of the COM
object. CComObject<>, CComAggObject<>, CComObjectCached<>, CComObjectNoLock<> are
some of CComObjectxxx<> classes.
ATL uses the Strategy Pattern to encapsulate the behavior in different CComObjectxxx<>
classes and the COM class can select the required CComObjectxxx<> based on the functionality
needed. Since, there is no need to change a Strategy at run-time; ATL uses C++ template for the
implementation of the Strategy Pattern. ATL selects a Strategy (CComObjectxxx<>) and
passes the Context (CMyClass) as a parameter to the Strategy.
Java and Strategy Pattern
Strategy Pattern is also used in the implementation of the Layout Manager in Java. The Layout
manager can be configured with a layout object, which can be an object of a FlowLayout, a
CardLayout, a GridLayout or a GridBagLayout class. These classes encapsulate the algorithms for
laying out visual components and they provide several different layouts for viewing the same
visual widgets.
Other known uses
Borland's ObjectWindows uses strategies to encapsulate validation algorithms for dialog box
entry fields. For example, a numeric field might have a validator to check proper range, a date
field might have a validator to check the correctness of the input date and string field might have
a validator for proper syntax.
ET++ uses the Strategy Pattern to encapsulate layout algorithms for text viewers.
Strategy Pattern is also used in many popular sorting algorithms, graph layout algorithms and
memory allocation algorithms.
Bridge and Strategy
Often, the Strategy Pattern is confused with the Bridge Pattern. Even though, these two patterns
are similar in structure, they are trying to solve two different design problems. Strategy is mainly
concerned in encapsulating algorithms, whereas Bridge decouples the abstraction from the
implementation, to provide different implementation for the same abstraction.
Summary
This article is all about the Strategy Pattern, it not only talked about what Strategy Pattern is,
but also emphasized why and when it is needed. I have used this pattern in many of my projects
including the implementation of Lexical Analyzer and Parser classes. This pattern can be applied
wherever there are several different ways of performing the same task. In short, the Strategy
Pattern can be used to encapsulate varying algorithms and use them to change the system
behavior without altering its architecture.
Acknowledgments
Special thanks to my friend Sree Meenakshi for her helpful suggestions in improving the clarity
and presentation of this article.
Listing 1 - Strategy object as a required
parameter to the Context
Collapse | Copy Code
// Forward declaration for CFiller class
class CFiller;

// Class declaration for CProgressIndicator
class CProgressIndicator
{
// Method declarations
public:
CProgressIndicator(CFiller *);
INT SetPos(INT);
INT SetFiller(CFiller *);


// Data members
protected:
CFiller * m_pFiller;
};

// CProgressIndicator - Implementation
CProgressIndicator ::CProgressIndicator(CFiller * pFiller)
{
// Validate pFiller
ASSERT(pFiller != NULL);
m_pFiller = pFiller;
}

INT CProgressIndicator ::SetPos(INT nPos)
{
// Some initialization code before forwarding the request to filler object


// Request forwarding to filler object
INT nStatus = m_pFiller->DoFill();


return nStatus;
}

INT * CProgressIndicator ::SetFiller(CFiller * pFiller)
{
// Validate pFiller
ASSERT(pFiller != NULL);
// Set new filler object
m_pFiller = pFiller;
return 0;
}
Listing 2 - Strategy object as an optional
parameter to the Context
Collapse | Copy Code
// Forward declaration for CFiller class
class CFiller;

// Class declaration for CProgressIndicator
class CProgressIndicator
{
// Method declarations
public:
CProgressIndicator(CFiller * = NULL);
virtual ~CProgressIndicator();
INT SetPos(INT);
INT SetFiller(CFiller *);



// Data members
protected:
CFiller * m_pFiller;
BOOL m_bCreated;
};

// CProgressIndicator - Implementation
CProgressIndicator ::CProgressIndicator(CFiller * pFiller)
{
// Check and create filler object
if(pFiller == NULL)
{
// Create a default Left to Right filler object
m_pFiller = new CLToRFiller;
m_bCreated = TRUE;
}
else
{
m_pFiller = pFiller;
m_bCreated = FALSE;
}
}

CProgressIndicator::~CProgressIndicator()
{
// Delete filler object, only if it is created by the progress indicator
if(m_bCreated == TRUE)
{
delete m_pFiller;
}
}

INT CProgressIndicator ::SetPos(INT nPos)
{
// Some initialization code before forwarding the request to CFiller object
ASSERT(m_pFiller != NULL);


// Request forwarding to CFiller object
INT nStatus = m_pFiller->DoFill();


return nStatus;
}

INT * CProgressIndicator ::SetFiller(CFiller * pFiller)
{
// Validate Filler object
ASSERT(pFiller != NULL);
// Delete filler object, only if it is created by the progress indicator
if(m_bCreated == TRUE)
{
delete m_pFiller;
m_bCreated = FALSE;
}
// Set new filler object
m_pFiller = pFiller;
return 0;
}
Listing 3 - Strategy as a template class
parameter
Collapse | Copy Code
template <class TFiller> class CProgressIndicator
{
// Method declarations
public:
INT SetPos(INT);


// Data members
protected:
TFiller m_theFiller;
};

// CProgressIndicator - Implementation

INT CProgressIndicator ::SetPos(INT nPos)
{
// Some initialization code before forwarding the request to CFiller
// object


// Request forwarding to CFiller object
INT nStatus = m_theFiller.DoFill();


return nStatus;
}

// Application code using CProgressIndicator

CProgressIndicator<CLToRFiller> LtoRFillerObj;
License
This article has no explicit license attached to it but may contain usage terms in the article text or
the download files themselves. If in doubt please contact the author via the discussion board
below.

You might also like