Software Design Patterns Made Simple
Software Design Patterns Made Simple
Part I............................................................................................................................................................4
Introduction.................................................................................................................................................4
Introduction To This Article.....................................................................................................................4
An Overview of Design Patterns..............................................................................................................4
Architecting Your (Simple) Football Engine..................................................................................................5
Identifying Entities....................................................................................................................................5
Identifying Design Problems....................................................................................................................6
Identifying Patterns To Use..........................................................................................................................7
1: Addressing the design problems related with the 'Ball'......................................................................7
2: Addressing the design problems related with 'Team' And 'TeamStrategy'.........................................7
3: Addressing the design problems related with 'Player'........................................................................8
4: Addressing the design problems related with 'PlayGround'.................................................................8
Part II...........................................................................................................................................................9
Applying Observer Pattern............................................................................................................................9
Understanding the Observer Pattern........................................................................................................9
Adapting the Observer Pattern..............................................................................................................11
Ball (Subject)......................................................................................................................................12
FootBall (ConcreteSubject).................................................................................................................12
IObserver (Observer)..........................................................................................................................13
Player (ConcreteObserver).................................................................................................................13
Referee (ConcreteObserver)...............................................................................................................14
Position Class.....................................................................................................................................15
Putting It All Together........................................................................................................................15
Running the project...........................................................................................................................16
Classification..............................................................................................................................................17
Part III........................................................................................................................................................18
Applying Strategy Pattern..........................................................................................................................18
Understanding the Strategy Pattern.......................................................................................................18
Adapting the Strategy Pattern................................................................................................................19
Strategy Pattern Implementation............................................................................................................20
TeamStrategy (Strategy).....................................................................................................................20
AttackStrategy (ConcreteStrategy).....................................................................................................20
DefendStrategy (ConcreteStrategy)....................................................................................................20
Team (Context)..................................................................................................................................21
Putting It All Together........................................................................................................................21
Running The Project...........................................................................................................................22
Part IV........................................................................................................................................................23
Applying Decorator Pattern........................................................................................................................23
Understanding Decorator Pattern...........................................................................................................23
Adapting The Decorator Pattern............................................................................................................24
Decorator Pattern Implementation.........................................................................................................26
Player (Component)...........................................................................................................................26
FieldPlayer (ConcreteComponent).....................................................................................................26
GoalKeeper (ConcreteComponent)....................................................................................................26
PlayerRole (Decorator).......................................................................................................................27
Forward (ConcreteDecorator)............................................................................................................27
MidFielder (ConcreteDecorator)..........................................................................................................28
Defender (ConcreteDecorator)...........................................................................................................28
Putting It All Together........................................................................................................................28
Running The Project...........................................................................................................................30
Part I
Introduction
Introduction To This Article
As a prerequisite
You may need to get some grip on reading and understanding UML diagrams
The related zip file includes the code, UML designs (in Visio format) etc. After reading
this article, you may download and extract the zip file - using a program like Winzip -
to play with the source code.
Even without much knowledge about design patterns, designers and developers tend to
reuse class relationships and object collaborations to simplify the design process. In short,
"A Design pattern consists of various co-operating objects (classes, relationships etc)". They
provide solutions for common design problems. More than anything else, they offer a
consistent idiom for designers and programmers to speak about their design. For example,
you can tell a friend that you used a 'Builder' pattern for addressing some design
specifications in your project.
A consistent classification of patterns for common design problems are provided by Erich
Gamma, Richard Helm, Ralph Johnson, and John Vlissides [also known as the Gang of Four
(GOF)]. The Gang of Four (GOF) patterns are generally considered the foundation for all
other patterns.
The basic principle of using patterns is reusability. Once a problem is address some way,
you are not really expected to re-invent the wheel if you properly understand the concept of
pattern centric software engineering. Here are some important points to remember about
design patterns.
A Design Pattern is not code. It is in fact an approach or a model that can be used to
solve a problem.
Design Patterns are about design and interaction of objects and they provide
reusable solutions for solving common design problems.
A Design Pattern is normally represented with the help of a UML diagram.
Some real hands on experience with patterns may provide you a better idea!!
Identifying Entities
First of all, you need to identify the objects you use in your game engine. For this, you
should visualize how the end user is going to use the system. Let us assume that the end
user is going to operate the game in the following sequence (let us keep things simple).
Your system may have a number of PlayGrounds in it, a number of Teams etc. To list a few
real world objects in the system, you have
Game which defines a football game, which constitutes teams, ball, referee,
playground etc
GameEngine to simulate a number of games at a time.
TeamStrategy to decide a team's strategy while playing
So, here is a very abstract view of the system. The boxes represent classes in your system,
and the connectors depicts 'has' relationships and their multiplicity. The arrow head
represents the direction of reading. I.e, a GameEngine has (can simulate) Games. A Game
has (consists of) three referees, one ball, two teams, and one ground. A team can have
multiple players, and one strategy at a time.
First of all, you have to write down a minimum description of your soccer engine, to identify
the design problems. For example, here are few design problems related to some of the
objects we identified earlier.
Ball
o When the position of a ball changes, all the players and the referee should be
notified straight away.
Team and TeamStrategy
o When the game is in progress, the end user can change the strategy of his
team (E.g., From Attack to Defend)
Player
o A player in a team should have additional responsibilities, like Forward,
Defender etc, that can be assigned during the runtime.
PlayGround
o Each ground constitutes of gallery, ground surface, audience, etc - and each
ground has a different appearance.
So now, let us see how to identify the patterns, to address these design problems.
First of all, take the specifications related to the ball. You need to design a framework such
that when the state (position) of the ball is changed, all the players and the referee are
notified regarding the new state (position) of the ball. Now, let us generalize the problem
Specific Design Problem: "When the position of a ball changes, all the players and the
referee should be notified straight away."
Problem Generalized: "When a subject (in this case, the ball) changes, all its dependents
(in this case, the players) are notified and updated automatically."
Once you have such a design problem, you refer the GOF patterns - and suddenly you may
find out that you can apply the 'Observer' pattern to solve the problem.
Observer Pattern: Define a one-to-many dependency between objects so that when one
object changes state, all its dependents are notified and updated automatically.
In this case, we used this pattern because we need to notify all the players, when the
position of the ball is changed.
Next, we have to address the specifications related to the team and team strategy. As we
discussed earlier, when the game is in progress, the end user can change the strategy of his
team (E.g., From Attack to Defend). This clearly means that we need to separate the
Team's Strategy from the Team that uses it.
Specific Design Problem: "When the game is in progress, the end user can change the
strategy of his team (E.g., From Attack to Defend)"
Problem Generalized: "We need to let the algorithm (TeamStrategy) vary independently
from clients (in this case, the Team) that use it."
Then, you can chose the 'Strategy' pattern to address the above design problem.
Strategy Pattern: Define a family of algorithms, encapsulate each one, and make them interchangeable. S
that use it.
Now, let us address the design specifications related to the player. From our problem
definition, it is clear that we need to assign responsibilities (like forward, defender etc) to
each player during run time. At this point, you can think about sub classing (i.e,
inheritance) - by creating a player class, and then inheriting classes like Forward, Defender
etc from the base class. But the disadvantage is that, when you do sub classing, you cannot
separate the responsibility of an object from its implementation.
I. e, In our case, sub classing is not the suitable method, because we need to separate the
responsibilities like 'Forward', 'Midfielder', 'Defender' etc from the Player implementation.
Because, a player can be a 'Forward' one time, and some other time, the same player can
be a 'Midfielder'.
Specific Design Problem: "A player in a team should have additional responsibilities, like
Forward, Defender etc, that can be assigned during the runtime."
Then, you can chose the 'Decorator' pattern to address the above design problem.
Decorator Pattern: Attach additional responsibilities to an object dynamically. Decorators provide a flexible
If you take a look at the specifications of Ground, we see that a ground's appearance is
decided by various sub units like gallery, surface of the ground, audience etc. The
appearance of the ground may vary, according to these sub units. Hence, we need to
construct the ground in such a way that, the construction of the ground can create different
representations of the ground. I.e, a ground in Italy may have different gallery structure
and surface when compared to a ground in England. But, the game engine may create both
these grounds by calling the same set of functions.
Specific Design Problem: "Each ground constitutes of gallery, ground surface, audience,
etc - and each ground has a different appearance."
Problem Generalized: "We need to separate the construction of an object (ground) from
its representation (the appearance of the ground) and we need to use the same
construction process to create different representations."
Builder Pattern: Separate the construction of a complex object from its representation so that the same co
representations.
Now, you can chose the 'Builder' pattern to address the above design problem.
Part II
Dumb Developer: "Yes, now I can develop a football engine using patterns"
"When the position of a ball changes, all the players should be notified straight
away."
▪ Subject
This class provides an interface for attaching and detaching observers. Subject class
also holds a private list of observers. Functions in Subject class are
▪ Attach - To add a new observer to the list of observers observing the subject
▪ Detach - To remove an observer from the list of observers observing the
subject
▪ Notify- To notify each observer by calling the Update function in the
observer, when a change occurs.
▪ ConcreteSubject
This class provides the state of interest to observers. It also sends a notification to
all observers, by calling the Notify function in its super class (i.e, in the Subject
class). Functions in ConcreteSubject class are
▪ Observer
This class defines an updating interface for all observers, to receive update
notification from the subject. The Observer class is used as an abstract class to
implement concrete observers
▪ ConcreteObserver
This class maintains a reference with the subject, to receive the state of the subject
when a notification is received.
▪ Update - This is the overridden function in the concrete class. When this
function is called by the subject, the ConcreteObserver calls the
GetState function of the subject to update the information it have about the
subject's state.
Now, let us see how this pattern can be adapted to solve our specific problem. This will give
you a better idea.
Fig 3 - Solving Our First Design Problem
When we call the SetBallPosition function of the ball to set the new position, it inturn
calls the Notify function defined in the Ball class. The Notify function iterates all observers
in the list, and invokes the Update function in each of them. When the Update function is
invoked, the observers will obtain the new state position of the ball, by calling the
GetBallPosition function in the Foot ball class.
Ball (Subject)
Public Sub
NotifyObservers() Dim o As
IObserver
For Each o In observers
o.Update()
Next
End
Sub
'State: The position of the ball
'Some external client will call this to set the ball's position
NotifyObservers()
End Function
IObserver (Observer)
The implementation of IObserver class is shown below. This class provides interface
specifications for creating Concrete Observers.
'Player
Update()inherits from IObserver, and overrides Update method
Referee (ConcreteObserver)
The implementation of Referee class is shown below. Referee is also inherited from
IObserver class
Public Class
Referee Inherits
IObserver
Position Class
Dim
Me.Xball
= As New FootBall()
x Me.Y
'Create
= y few players (i.e, ConcreteObservers)
Me.Z =
Dim
Z Owen As New Player(ball, "Owen")
Dim
End Ronaldo
Sub As New Player(ball, "Ronaldo")
Dim Rivaldo As New Player(ball, "Rivaldo")
'Create few referees (i.e, ConcreteObservers)
ball.AttachObserver(Owen)
ball.AttachObserver(Ronaldo
)
ball.AttachObserver(Rivaldo
) ball.AttachObserver(Mike)
ball.AttachObserver(John)
ball.SetBallPosition(New Position())
System.Console.WriteLine()
ball.DetachObserver(Owen)
ball.DetachObserver(John)
System.Console.Read()
End Sub
With respect to purpose, patterns are classified to Creational, Structural and Behavioral. For
example,
Specific Design Problem: "When the game is in progress, the end user can change
the strategy of his team (E.g., From Attack to Defend)"
Problem Generalized: "We need to let the algorithm (TeamStrategy) vary
independently from clients (in this case, the Team) that use it."
As we discussed earlier, when the game is in progress, we need to change the strategy of
the team (E.g., From Attack to Defend). This clearly means that we need to separate the
Team's Strategy from the Team that uses it.
As we know, we can apply strategy pattern to solve the above design problem, because it
lets the algorithm (i.e, the Team's strategy) vary independently from clients (i.e, the Team)
that use it. Let us see how we can apply Strategy pattern to solve this design problem.
Strategy pattern is pretty simple. The UML diagram of Strategy Pattern is shown below.
Strategy
This class is an abstract class for the algorithm (or strategy), from which all concrete
algorithms are derived. In short, it provides an interface common to all the concrete
algorithms (or concrete strategies). I.e, if there an abstract (must override) function called
foo() in the Strategy class, all concrete strategy classes should override the foo() function.
ConcreteStrategy
This class is where we actually implement our algorithm. In other words, it is the concrete
implementation of the Strategy class. Just for an example, if Sort is the strategy class which
implements the algorithm, then the concrete strategies can be MergeSort, QuickSort etc
Context
This Context can be configured with one or more concrete strategy. It will access the
concrete strategy object through the strategy interface.
Now, let us see how we actually adapt the Strategy pattern, to solve our problem. This will
give you a very clear picture.
Here, the TeamStrategy class holds the Play function. AttackStrategy and
DefendStrategy are the concrete implementations of the TeamStrategy class. The Team
holds a strategy, and this strategy can be changed according to the situation of the match
(for example, we change the active strategy from AttackStrategy to DefendStrategy, if we
lead by a number of goals - huh, well, I'm not a good football coach anyway). When we call
PlayGame function in the Team, it calls the Play function of the current strategy. Kindly
have a look at the code. It is straight forward, and everything is commented neatly.
By using strategy pattern, we separated the algorithm (i.e, the strategy of the team) from
the Team class.
TeamStrategy (Strategy)
Team (Context)
The code for Team class is shown below. A team can have one strategy at a time, according
to our design.
'Function to play
Public Sub PlayGame()
'Print the team's
name
System.Console.WriteLine(teamName)
'Play according to the strategy
strategy.Play()
End Sub
System.Console.WriteLine()
System.Console.WriteLine("Changing the strategies..")
End Sub
Running The Project
You can think about creating a player class, and then deriving sub classes like Forward,
Midfielder, Defender etc. But it is not the best solution, because as we discussed earlier - a
player can be a forward at one time, and at some other time, the same player can be a mid
fielder. At least, it will be so in our soccer engine. (any football experts around? ;) ) . So,
these were our design problems.
Specific Design Problem: "A player in a team should have additional responsibilities, like
Forward, Defender etc, that can be assigned during the runtime."
Decorator pattern can be used to add responsibilities to objects dynamically. They also
provide an excellent alternative to sub classing. The UML diagram of Decorator pattern is
shown below.
Fig - Decorator Pattern
Component
The Component class indicates an abstract interface for components. Later, we attach
additional responsibilities to these components.
ConcreteComponent
Decorator
Decorator class is derived from Component class. That means, it inherits all the interfaces
(functions, properties etc) of the component. It also keeps a reference to an object which is
inherited from the component class. Hence, one concrete decorator can keep references to
other concrete decorators as well (because Decorator class is inherited from the Component
class).
Concrete Decorator
This class is the actual place where we attach responsibilities to the component.
You can see that we have two concrete components, GoalKeeper and FieldPlayer,
inherited from the Player class. We have three concrete decorators, Forward, MidFielder,
and Defender. For a team, we may need 11 Field players and one goal keeper. Our design
intend is, we need to assign responsibilities like Forward, Defender etc to the players during
run time. We have only 11 field players - but it is possible that we can have 11 forwards
and 11 midfielders at the same time, because a single player can be a forward and a
midfielder at the same time. This will enable us to formulate good playing strategies - by
assigning multiple roles to players, by swapping their roles etc.
For example, you can ask a player to go forward and shoot a goal at some point of the
match, by temporarily assigning him to a Forward decorator.
To give additional responsibilities to a concrete component, first you create an object of the
concrete component, and then you will assign it as the reference of a decorator. For
example, you can create a field player and a Mid fielder decorator, and then you can assign
the field player to the mid fielder decorator to add the responsibility of mid fielder to your
player. Later, if you want, you can assign the same player to an object of a Forward
decorator. This is very well explained in the GameEngine module of the Decorator pattern
sample code.
See the implementation below. It is heavily commented.
Player (Component)
The implementation
'Just of FieldPlayer
give a name for class is shown below
this player
Private myName As String
' ConcreteComponent
'The : Field
property to get/set thePlayer
name class
GoalKeeper (ConcreteComponent)
Public Property Name() As String
'This is a concrete component. Later, we will add additional
Get
responsibilities 'like Forward, Defender etc to a field player.
Return
myName End
Public Class FieldPlayer
Get
Inherits Player
Set(ByVal Value As String)
myName = Value
'Operation: Overrides PassBall operation
End Set
Public Overrides Sub PassBall ()
End Property
System.Console.WriteLine(" Fieldplayer ({0}) - passed the ball",
_ MyBase.Name)
'This is the Operation in the component
End Sub
'and this will be overrided by concrete components
Public MustOverride Sub PassBall()
'A constructor to accept the name of the player
Public Sub New(ByVal playerName As String)
MyBase.Name = playerName
End Sub
End Sub
MidFielder (ConcreteDecorator)
'-- Step 2:
'Just make them pass the ball
'(during a warm up session ;))
System.Console.WriteLine()
System.Console.WriteLine(" > Warm up Session... ")
owen.PassBall()
beck.PassBall()
khan.PassBall()
System.Console.WriteLine()
System.Console.WriteLine(" > Match is starting.. ")
System.Console.WriteLine()
System.Console.WriteLine(" > OOps, Owen got injured. " & _
"Jerrard replaced Owen.. ")
System.Console.WriteLine()
System.Console.WriteLine(" > Beckham has multiple responsibilities.. ")
End Sub
End