Daily Design Pattern
Daily Design Pattern
TABLE OF CONTENTS
Day 0: Introduction ..................................................................................... 2
Day 1: The Factory Method Design Pattern ...................................................... 3
Day 2: The Abstract Factory Design Pattern ..................................................... 8
Day 3: The Façade Design Pattern ............................................................... 13
Day 4: The Adapter Design Pattern .............................................................. 20
Day 5: The Bridge Design Pattern ................................................................ 27
Day 6: The Template Method Design Pattern ................................................. 33
Day 7: The Iterator Design Pattern .............................................................. 39
Day 8: The Observer Design Pattern............................................................. 44
Day 9: The Memento Design Pattern ............................................................ 50
Day 10: The Prototype Design Pattern .......................................................... 55
Day 11: The Singleton Design Pattern .......................................................... 60
Day 12: The Flyweight Design Pattern .......................................................... 63
Day 13: The Builder Design Pattern .............................................................. 71
Day 14: The State Design Pattern ................................................................ 79
Day 15: The Strategy Design Pattern............................................................ 90
Day 16: The Proxy Design Pattern................................................................ 96
Day 17: The Decorator Design Pattern ......................................................... 100
Day 18: Chain of Responsibility Design Pattern ............................................. 107
Day 19: The Visitor Design Pattern.............................................................. 112
Day 20: The Composite Design Pattern ........................................................ 118
Day 21: The Mediator Design Pattern .......................................................... 124
Day 22: The Command Design Pattern ........................................................ 130
Day 23: Wrapping Up................................................................................ 137
Page 1
Matthew P Jones The Daily Design Pattern
DAY 0: INTRODUCTION
Welcome to the Daily Design Pattern! This book is designed to help you learn and
demonstrate some of the most common and useful software design patterns in our
field.
One of the hallmarks of learning about software development is the realization that,
as time goes on, the syntax and details about implementation for any given software
project will change, but the fundamental concepts and ideals behind the code remain
relatively constant. This book aims to build up the fundamentals for any software
developer, but particularly for those familiar with C# or wishing to learn it. The
examples in this book are written in C# using .NET projects, but the code is
specifically designed so as to be readable by people who might not be familiar with
C# syntax. In short, I believe the examples herein will be useful to a great many
developers, not just C# ones.
Page 2
Matthew P Jones The Daily Design Pattern
The Factory Method pattern is a Creational pattern which defines an interface for
creating an object, but doesn't specify what objects the individual implementations
of that interface will instantiate.
All that means is that when using this pattern, you can define certain methods and
properties of object that will be common to all objects created using the Factory
Method, but let the individual Factory Methods define what specific objects they will
instantiate.
THE RUNDOWN
• Type: Creational
• Good For: Creating objects in a related family.
• Example Code: On GitHub
THE PARTICIPANTS
• The Product defines the
interfaces of objects that the
factory method will create.
• The ConcreteProduct objects
implement the Product
interface.
• The Creator declares the
factory method, which returns
an object of type Product. The
Creator can also define a
default implementation of the
factory method, though we will
not see that in the below example.
• The ConcreteCreator objects overrides the factory method to return an
instance of a Concrete Product.
A DELICIOUS EXAMPLE
To demonstrate how this pattern works, let’s talk about sandwiches.
Page 3
Matthew P Jones The Daily Design Pattern
“...is a food item consisting of one or more types of food, such as vegetables, sliced
cheese or meat, placed on or between slices of bread, or more generally any dish
wherein two or more pieces of bread serve as a container or wrapper for some other
food.”
For this day’s exercise, we'll assume that Sandwiches are comprised of Ingredients.
We'll need an abstract class Ingredient to represent this, and said Ingredient class
does double-duty as our Product participant:
// Product
abstract class Ingredient { }
Of course, sandwiches are never comprised of only one ingredient. Let’s also
instantiate a few classes to represent common ingredients, which will also be
our ConcreteProduct participants:
// Concrete Product
class Bread : Ingredient { }
// Concrete Product
class Turkey : Ingredient { }
// Concrete Product
class Lettuce : Ingredient { }
// Concrete Product
class Mayonnaise : Ingredient { }
Page 4
Matthew P Jones The Daily Design Pattern
With our Product and ConcreteProduct participants defined, what we now want to
do is build a factory that will allow us to build different kinds of sandwiches using the
same set of ingredients. What will differ between the kinds of sandwiches will be the
amount and order of said ingredients.
First, let's build an abstract class Sandwich that represents all possible kinds of
sandwiches (this is the Creator participant):
// Creator
abstract class Sandwich
{
private List<Ingredient> _ingredients = new List<Ingredient>();
public Sandwich()
{
CreateIngredients();
}
//Factory method
public abstract void CreateIngredients();
Note the CreateIngredients() method; this method is the Factory Method which
gives the pattern its name. It's not implemented here because that implementation
is left up to the ConcreteCreator classes that we now need to define.
Page 5
Matthew P Jones The Daily Design Pattern
Speaking of which, let’s actually do that implementation now. We can start off with
a basic turkey sandwich:
// Concrete Creator
class TurkeySandwich : Sandwich
{
public override void CreateIngredients()
{
Ingredients.Add(new Bread());
Ingredients.Add(new Mayonnaise());
Ingredients.Add(new Lettuce());
Ingredients.Add(new Turkey());
Ingredients.Add(new Turkey());
Ingredients.Add(new Bread());
}
}
Page 6
Matthew P Jones The Daily Design Pattern
// Concrete Creator
class Dagwood : Sandwich //OM NOM NOM
{
public override void CreateIngredients()
{
Ingredients.Add(new Bread());
Ingredients.Add(new Turkey());
Ingredients.Add(new Turkey());
Ingredients.Add(new Lettuce());
Ingredients.Add(new Lettuce());
Ingredients.Add(new Mayonnaise());
Ingredients.Add(new Bread());
Ingredients.Add(new Turkey());
Ingredients.Add(new Turkey());
Ingredients.Add(new Lettuce());
Ingredients.Add(new Lettuce());
Ingredients.Add(new Mayonnaise());
Ingredients.Add(new Bread());
Ingredients.Add(new Turkey());
Ingredients.Add(new Turkey());
Ingredients.Add(new Lettuce());
Ingredients.Add(new Lettuce());
Ingredients.Add(new Mayonnaise());
Ingredients.Add(new Bread());
Ingredients.Add(new Turkey());
Ingredients.Add(new Turkey());
Ingredients.Add(new Lettuce());
Ingredients.Add(new Lettuce());
Ingredients.Add(new Mayonnaise());
Ingredients.Add(new Bread());
Ingredients.Add(new Turkey());
Ingredients.Add(new Turkey());
Ingredients.Add(new Lettuce());
Ingredients.Add(new Lettuce());
Ingredients.Add(new Mayonnaise());
Ingredients.Add(new Bread());
Ingredients.Add(new Turkey());
Ingredients.Add(new Turkey());
Ingredients.Add(new Lettuce());
Ingredients.Add(new Lettuce());
Ingredients.Add(new Mayonnaise());
Ingredients.Add(new Bread());
}
}
Page 7
Matthew P Jones The Daily Design Pattern
class Program
{
static void Main(string[] args)
{
var turkeySandwich = new TurkeySandwich();
var dagwood = new Dagwood();
//Do something with these sandwiches (like, say, eat them).
}
}
SUMMARY
The Factory Method Design Pattern provides a manner in which we can instantiate
objects, but the details of the creation of those instances are left to be defined by the
instance classes themselves. By using this pattern, we can create groups of related
classes easily and in an extensible fashion.
When using this pattern, you create factories which return many kinds of related
objects. This pattern enables larger architectures such as Dependency Injection.
THE RUNDOWN
• Type: Creational
• Good For: Creating objects in different related families without relying on
concrete implementations.
• Example Code: On GitHub
Page 8
Matthew P Jones The Daily Design Pattern
THE PARTICIPANTS
• The AbstractFactory declares
an interface for operations
which will create
AbstractProduct objects.
• The ConcreteFactory objects
implement the operations
defined by the AbstractFactory.
• The AbstractProduct declares
an interface for a type of
product.
• The Products define a product
object that will be created by
the corresponding
ConcreteFactory.
• The Client uses the
AbstractFactory and
AbstractProduct interfaces.
Don’t be scared off by this diagram! This pattern is not as complicated as it might
first appear.
A DELICIOUS EXAMPLE
When we modeled the Factory Method Pattern yesterday, we did so using
sandwiches. The thing about sandwiches is that they no matter what they are made
of (turkey, roast beef,
veggies, peanut butter
and jelly) they're still
sandwiches, e.g.
something edible
between two slices of
bread.
In that previous
example, sandwiches
could be considered a
family of related
objects. But what if
wanted to model several
families of objects, not just one?
For this demo, let's go more general and model entire sets of recipes.
Let's say we want to model two kinds of recipes: Sandwich and Dessert. Further, let's
make the assumption that adults and kids don't eat the same things, and so we want
one of each kind of recipe for adults and children.
Page 9
Matthew P Jones The Daily Design Pattern
To demo this, let's make some abstract classes representing the generic kinds of
recipes (these are our AbstractProduct participants):
// AbstractProduct
abstract class Sandwich { }
// AbstractProduct
abstract class Dessert { }
Next, we need an abstract class that will return a Sandwich and a Dessert (this is
the AbstractFactory participant):
Now we can start implementing the actual sandwiches and desserts as C# classes.
First let's consider the adult menu, where the more “grown up” tastes for adults might
result in us serving a BLT for a sandwich and Crème Brulee for dessert (the classes
for which would be ConcreteProduct participants):
// ConcreteProduct
class BLT : Sandwich { }
// ConcreteProduct
class CremeBrulee : Dessert { }
Page 10
Matthew P Jones The Daily Design Pattern
// ConcreteFactory
class AdultCuisineFactory : RecipeFactory
{
public override Sandwich CreateSandwich()
{
return new BLT();
}
Now let's define the recipes for children. Here are the ConcreteProduct and
ConcreteFactory classes available to feed those hungry kiddos:
// Concrete Product
class GrilledCheese : Sandwich { }
// Concrete Product
class IceCreamSundae : Dessert { }
// Concrete Factory
class KidCuisineFactory : RecipeFactory
{
public override Sandwich CreateSandwich()
{
return new GrilledCheese();
}
With all of our pattern participants defined, we now need to ask the most important
question: how do we actually use this thing?
Page 11
Matthew P Jones The Daily Design Pattern
We’re going to create a simple C# program that asks the user if they are an adult or
a child displays the corresponding menu items. Said program might look like this:
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Who are you? (A)dult or (C)hild?");
char input = Console.ReadKey().KeyChar;
RecipeFactory factory;
switch(input)
{
case 'A':
factory = new AdultCuisineFactory();
break;
case 'C':
factory = new KidCuisineFactory();
break;
default:
throw new NotImplementedException();
Console.ReadKey();
}
}
When we run the app, the output looks something like the examples on the next
page.
Page 12
Matthew P Jones The Daily Design Pattern
Ta-da! We now have a working example of the Abstract Factory Design Pattern!
That said, it's also one of the patterns that's prone to overuse: it's easy to start using
Abstract Factories anytime you need to create objects. Be aware of when you decide
to use this pattern, and make sure you actually need it.
SUMMARY
Abstract Factory allows us to generically define families of related objects, leaving
the actual concretions for those objects to be implemented as needed. This is similar
to the Factory Method Pattern from Day 1, with a different scope; whereas Factory
Method Pattern allows us to create many related objects, Abstract Factory Pattern
allows us to create groups of related objects.
Page 13
Matthew P Jones The Daily Design Pattern
The Façade Design Pattern is one of the simpler patterns in the Gang of Four book.
In essence, it is a simple structure laid over a more complex structure, in order to
limit the accessibility of the “hidden” functionality in the complex structure from other
objects that might be calling it.
The idea is that if you don't want other code accessing the complex bits of a class or
process, you hide those bits by covering them with a Façade.
Oh, and please note: it is pronounced “fah-sahd” not “fah-kayd”. Don’t make the
same mistake I did.
THE RUNDOWN
• Type: Structural
• Good For: Hiding complexity which cannot be refactored away.
• Example Code: On GitHub
THE PARTICIPANTS
• The Subsystems are any
classes or objects which
implement functionality but
can be "wrapped" or "covered"
by the Facade to simplify an
interface.
• The Facade is the layer of
abstraction above the
Subsystems, and knows which
Subsystem to delegate
appropriate work to.
A DELICIOUS EXAMPLE
To demonstrate how we use the Façade pattern, let’s think about a restaurant.
In most modern, professional kitchens, the work area is divided into sections. For
this day’s example, we’ll assume that our kitchen is divided into three areas: Hot
Prep, where hot dishes like meat and pasta are made; Cold Prep, where cold dishes
like salads and desserts are made; and the Bar, where drinks are prepared.
If you are a customer at this restaurant and you sit down in a booth one evening,
ready to eat a delicious meal, do you care what part of said meal is made at which
section of the restaurant? Of course not!
This is because there is a natural layer of abstraction in place between yourself and
the kitchen: the server.
Page 14
Matthew P Jones The Daily Design Pattern
First, let's create a class for the restaurant patron (example code on next page):
Page 15
Matthew P Jones The Daily Design Pattern
We will also need to define three more things: a base class representing all food items
sold at this restaurant; an interface representing all sections of this restaurant's
kitchen; and a class representing a patron's order. That example code is as follows:
Page 16
Matthew P Jones The Daily Design Pattern
We can now start to model the sections of the kitchen, AKA the Subsystem
participants. Here's the classes for ColdPrep, HotPrep, and Bar:
Page 17
Matthew P Jones The Daily Design Pattern
Finally, we need the actual Façade participant, which is our Server class:
order.Appetizer = _coldPrep.PrepDish(coldAppID);
order.Entree = _hotPrep.PrepDish(hotEntreeID);
order.Drink = _bar.PrepDish(drinkID);
return order;
}
}
Page 18
Matthew P Jones The Daily Design Pattern
With all of these classes and objects in place, we can use the Main() method in our
Program.cs file to show how a patron might place an order, and how the server (the
Facade) would direct the appropriate pieces of that order to the kitchen sections (the
Subsystems):
Console.ReadKey();
}
If we run the sample app, our output might look like this:
Page 19
Matthew P Jones The Daily Design Pattern
WILL I EVER
NEED THIS
PATTERN?
All the time.
Seriously, the
Facade pattern is
so general that it
applies to almost
every major app
I've worked on,
especially those where I couldn't refactor or modify pieces of said apps for various
reasons.
SUMMARY
The Façade Design Pattern is a simple (or at least simpler) overlay on top of a group
of more complex subsystems. In effect, it introduces a layer of abstraction into the
design so that one layer doesn’t have access to more than it needs in the lower layer.
This pattern is very, very common, so it's one of the patterns we software developers
should know and understand thoroughly.
The Adapter Design Pattern attempts to reconcile the differences between two
otherwise-incompatible interfaces. It does this by introducing a third interface which
“interacts” between the two incompatible ones.
THE RUNDOWN
• Type: Structural
• Good For: Adapting two interfaces together when one or more of those
interfaces cannot be refactored.
• Example Code: On GitHub
Page 20
Matthew P Jones The Daily Design Pattern
THE PARTICIPANTS
• The Target defines the
domain-specific interface in
use by the Client.
• The Client collaborates
with objects which conform
to the Target.
• The Adapter adapts the
Adaptee to the Target.
• The Adaptee is the
interface that needs
adapting (i.e. the one that cannot be refactored).
A DELICIOUS EXAMPLE
Vegetarians beware; for this demo, we’re going to cook some meat.
Let’s say our old system must keep cooking temperatures in both Fahrenheit and
Celsius. We can use a C# enumeration to keep track of that:
Page 21
Matthew P Jones The Daily Design Pattern
We also need the actual implementation of this old system. To start, we might have
a method which returns the safe cook temperature in both Fahrenheit and Celsius for
various kinds of meat:
class MeatDatabase
{
public float GetSafeCookTemp(string meat,
TemperatureType tempType)
{
if (tempType == TemperatureType.Fahrenheit)
{
switch (meat)
{
case "beef":
case "pork":
return 145f;
case "chicken":
case "turkey":
return 165f;
default:
return 165f;
}
}
else
{
switch (meat)
{
case "beef":
case "veal":
case "pork":
return 63f;
case "chicken":
case "turkey":
return 74f;
default:
return 74f;
}
}
}
}
Page 22
Matthew P Jones The Daily Design Pattern
We also have two methods which return the calories and protein per ounce of various
meats:
As you have most likely noticed, this old system does not properly model its objects
in an object-oriented fashion. Where this API returns results from methods, we know
that that data (safe cook temperature, calories per ounce, protein per ounce) should
really be properties in some kind of Meat object.
Page 23
Matthew P Jones The Daily Design Pattern
// Constructor
public Meat(string meat)
{
this.MeatName = meat;
}
In an ideal world, we would modify the existing API (the old system) to use this new
object and properly uphold object-oriented principles. But, for whatever reason, we
cannot actually change the old system, and must therefore introduce an Adapter
participant to use this pattern.
Page 24
Matthew P Jones The Daily Design Pattern
Said Adapter will be a class which inherits from our new Meat class but maintains a
reference to the API such that the API's data can be loaded into an instance of
the Meat class:
// Constructor
public MeatDetails(string name) : base(name) { }
SafeCookTempFahrenheit =
_meatDatabase.GetSafeCookTemp(MeatName,
TemperatureType.Fahrenheit);
SafeCookTempCelsius =
_meatDatabase.GetSafeCookTemp(MeatName,
TemperatureType.Celsius);
CaloriesPerOunce =
_meatDatabase.GetCaloriesPerOunce(MeatName);
ProteinPerOunce = _meatDatabase.GetProteinPerOunce(MeatName);
base.LoadData();
Console.WriteLine(" Safe Cook Temp (F): {0}",
SafeCookTempFahrenheit);
Console.WriteLine(" Safe Cook Temp (C): {0}",
SafeCookTempCelsius);
Console.WriteLine(" Calories per Ounce: {0}",
CaloriesPerOunce);
Console.WriteLine(" Protein per Ounce: {0}", ProteinPerOunce);
}
}
Page 25
Matthew P Jones The Daily Design Pattern
Finally, in our Program.cs file’s Main() method, we can now show the differences
between using the Target class by itself and using the Adapter class:
//Adapted
MeatDetails beef = new MeatDetails("Beef");
beef.LoadData();
Console.ReadKey();
}
Page 26
Matthew P Jones The Daily Design Pattern
SUMMARY
The Adapter pattern attempts to reconcile two incompatible interfaces, and is
especially useful when one or both of those interfaces cannot be refactored. It does
this by introducing a new interface which is used to communicate between a Target
participant and an Adaptee participant.
BACKGROUND
In object-oriented programming, the concept of inheritance is crucial to developing
objects. This binds the implementation to its abstraction, and often that's exactly
what we want. However, there can be scenarios in which one class inheriting from
another might not be the best solution, particularly when multiple inheritances can
be used. The Bridge can be used to reconcile this situation.
This design pattern is especially useful for scenarios in which changes to the
implementation of an object should have no bearing on how their clients use said
implementations. Bridge also differs from Adapter in that Bridge is used when
designing new systems while Adapter is used to adapt old systems to new ones.
THE RUNDOWN
• Type: Structural
• Good For: Allowing lots of variation between implementations of interfaces.
• Example Code: On GitHub
Page 27
Matthew P Jones The Daily Design Pattern
THE PARTICIPANTS
• The Abstraction defines an interface and maintains a reference to an
Implementor.
• The RefinedAbstraction extends the interface defined by the Abstraction.
• The Implementor defines the interface for the ConcreteImplementor objects.
This interface does not need to correspond to the Abstraction's interface.
• The ConcreteImplementor objects implement the Implementor interface.
A DELICIOUS EXAMPLE
In real life, my brother has Celiac
disease; this means that his body
cannot properly process gluten. He
cannot eat wheat, rye, barley, oats, or
anything made from any of those
ingredients, for if he does, he's
probably going to be unwillingly asleep
for the next six hours or so and could
cause permanent damage to his
digestive system.
Consequently, it can be
difficult for him to order a
meal from restaurants,
since often they don't
provide the proper special-
needs meal he needs (and
even if they do, the
environment in which the
food is prepped is often
not properly ventilated or
sterilized, making cross-
contamination likely).
The user of this system only needs to make two decisions: does s/he want a gluten-
free or dairy-free meal, and does s/he want it to come from a diner or a fancy
restaurant? The user should be able to make these decisions without needing to know
what specific restaurant or which specific meal will be ordered.
Page 28
Matthew P Jones The Daily Design Pattern
interface IOrder { }
class DairyFreeOrder : IOrder { }
class GlutenFreeOrder : IOrder { }
This is fine for simple implementations. But what if we also need to keep track of
what kind of restaurant the order came from? This is not directly related to what the
meal actually consists of, but is still a part of the model. In this case, we might end
up with a crazy inheritance tree:
interface IOrder { }
class DairyFreeOrder : IOrder { }
class GlutenFreeOrder : IOrder { }
interface IDinerOrder : IOrder { }
class DinerDairyFreeOrder : DairyFreeOrder, IDinerOrder { }
class DinerGlutenFreeOrder : GlutenFreeOrder, IDinerOrder { }
interface IFancyRestaurantOrder : IOrder { }
class FancyRestaurantDairyFreeOrder : DairyFreeOrder,
IFancyRestaurantOrder { }
class FancyRestaurantGlutenFreeOrder : GlutenFreeOrder,
IFancyRestaurantOrder { }
We’re trying to model two orthogonal properties (dairy-free vs gluten-free and diner
vs fancy restaurant) but this implementation leads us to have three interfaces and
six classes. This is overkill, way more code than we actually need.
Page 29
Matthew P Jones The Daily Design Pattern
interface IOrder { }
class DairyFreeOrder : IOrder { }
class GlutenFreeOrder : IOrder { }
interface IRestaurantOrder : IOrder { }
class DinerOrder : IRestaurantOrder { }
class FancyRestaurantOrder : IRestaurantOrder { }
We can expand this example code to fully implement the Bridge design pattern.
First, we need to write our Implementor participant, which will define a method for
placing an order:
We also need the Abstraction participant, which for this example is an abstract class
and will define a method for sending an order and keep a reference to the
Implementor:
Page 30
Matthew P Jones The Daily Design Pattern
Now we can start defining our RefinedAbstraction classes. For this demo, let's take
those two kinds of special-needs meals from earlier (dairy-free and gluten-free) and
implement RefinedAbstraction objects for them.
// RefinedAbstraction
public class SendDairyFreeOrder : SendOrder
{
public override void Send()
{
_restaurant.Place("Dairy-Free Order");
}
}
// RefinedAbstraction
public class SendGlutenFreeOrder : SendOrder
{
public override void Send()
{
_restaurant.Place("Gluten-Free Order");
}
}
Page 31
Matthew P Jones The Daily Design Pattern
We now need to define objects for the restaurants themselves (which are
our ConcreteImplementor participants).
Finally, we create a Main() method which uses the Bridge to create different orders
and send them to different restaurants.
Console.ReadKey();
}
If we run the app, we find that we can send any order to any restaurant. Further, if
any of the abstractions (the orders) change their definition, the implementors don't
Page 32
Matthew P Jones The Daily Design Pattern
actually care; and vice-versa, if the implementors change their implementation, the
abstractions don't need to change as well.
That said, this is one of those patterns where the complexity needed to implement it
may well cancel out its benefits. Don't forget to think critically about your situation
and determine if you really need a pattern before you start refactoring toward it!
SUMMARY
The Bridge design pattern seeks to allow abstractions and implementation to vary
independently. This becomes useful when dealing with situations where regular
inheritance would make us end up with too many classes.
Now, if only this kind of thing was easier to do in the real world…
The Template Method design pattern defines the outline or skeleton of an operation,
but leaves the specific steps involved to be defined by subclasses.
In other words, the Template Method pattern defines in what order certain steps
should occur, but can optionally leave the specific details of those steps to be
implemented by other classes. Whereas Factory Method in Day 1 did something
similar with creating objects, Template Method does this with the behavior of those
objects (hence why it is a behavioral pattern).
Page 33
Matthew P Jones The Daily Design Pattern
THE RUNDOWN
• Type: Behavioral
• Good For: Creating an outline of an algorithm but letting specific steps be
implemented by other classes.
• Example Code: On GitHub
THE PARTICIPANTS
• The AbstractClass defines a
set of abstract operations which
can (optionally) be implemented
by ConcreteClass objects. It also
implements a template method
which controls the order in
which those abstract operations
occur.
• The ConcreteClass objects
implement the operations
defined by the AbstractClass.
A DELICIOUS EXAMPLE
To properly demo this design pattern, let's talk about something humanity has been
doing for 30,000 years: baking bread.
There are easily hundreds of types of bread currently being made in the world, but
each kind involves specific steps in order to make them.
Page 34
Matthew P Jones The Daily Design Pattern
We want to model a few different kinds of bread that all use this same pattern, which
(no surprise) is a good fit for the Template Method design pattern.
Page 35
Matthew P Jones The Daily Design Pattern
First, let's create an AbstractClass Bread which represents all breads we can bake:
Notice that the MixIngredients() and Bake() methods are marked abstract, while
the Slice() method is marked virtual. This is intentional: the method by which
you slice bread is not likely to change depending on the kind of bread you make.
Further, the Make() method is the Template Method that gives this pattern its name.
Page 36
Matthew P Jones The Daily Design Pattern
Once we've defined a few types of bread, we can simulate making them in
our Main() method, like so:
Page 37
Matthew P Jones The Daily Design Pattern
Console.ReadKey();
}
That’s it! Template Method is (arguably) the simplest and most flexible of all the
behavioral design patterns, which is why it’s the first one we tackle in this book.
"While some gravitate towards the Singleton pattern to abuse after they learn the
GoF patterns, that wasn’t the case for me. Instead, I fell in love with the Template
[Method] Pattern. But there’s a problem with [this] pattern as the golden hammer
for every incidence of duplication we find in our application. The Template Method
favors inheritance over composition."
And, to be fair, he's right. Template Method forces a class to inherit from a class
rather than promoting object composition. If we're looking for strict-object-oriented
design, Template Method could be better replaced by other patterns we've yet to
cover, such as Strategy or Command.
But I'm not willing to go as far as saying "don't use Template Method." As with all
the other patterns, their applications depend on what problem you need to solve and
how you want to do so. Template Method is prone to over-use, so be careful with it.
SUMMARY
The Template Method design pattern allows for an object to set up a skeleton of an
algorithm but leave the implementation details up to the concrete classes to
implement.
Page 38
Matthew P Jones The Daily Design Pattern
The idea is that we'll have a class (the aptly-named "Iterator" class) which contains
a reference to a corresponding aggregate object, and that Iterator can traverse over
its aggregate to retrieve individual objects.
THE RUNDOWN
• Type: Behavioral
• Good For: Extracting objects from a collection without exposing the collection
itself.
• Example Code: On GitHub
THE PARTICIPANTS
• The Iterator defines an interface for accessing an Aggregate object and
traversing elements within that Aggregate.
• The ConcreteIterator implements the Iterator interface and keeps track of
its current position within the Aggregate.
• The Aggregate defines an interface for creating an Iterator object.
• The ConcreteAggregate implements the Iterator creation interface and
returns a ConcreteIterator for that ConcreteAggregate.
A DELICIOUS EXAMPLE
To demo how we might use the
Iterator design pattern, let's
talk about my favorite sugary
snack: jelly beans. So far as I
am concerned, these little
nuggets of sugar and flavor are
the best thing since sliced
bread (see Day 6).
Page 39
Matthew P Jones The Daily Design Pattern
class JellyBean
{
private string _flavor;
// Constructor
public JellyBean(string flavor)
{
this._flavor = flavor;
}
Page 40
Matthew P Jones The Daily Design Pattern
// Indexer
public object this[int index]
{
get { return _items[index]; }
set { _items.Add(value); }
}
}
Page 41
Matthew P Jones The Daily Design Pattern
Page 42
Matthew P Jones The Daily Design Pattern
Finally, in our Main(), we can create a collection of jelly beans and then iterate over
them:
// Create iterator
JellyBeanIterator iterator = collection.CreateIterator();
Console.ReadKey();
}
Now our Iterator class is able to iterate over the entire collection of jelly beans and
output their flavors!
Page 43
Matthew P Jones The Daily Design Pattern
you use LINQ, you are probably already using the Iterator design pattern extensively,
such as in collection.First() or collection.Count().
SUMMARY
The Iterator pattern provides a manner in which we can access and manipulate
objects in a collection without exposing the collection itself. This pattern is incredibly
common and incredibly useful, so keep it in mind; once you know what it is, you'll
start seeing it everywhere.
This means that a single object will need to be aware of the objects that observe it,
and need to be able to communicate to those observers that the subject's state
changed. Further, the observers should be notified automatically.
Also, I'm going to try to write this entire chapter without using the stupid phrase
"subject object" to describe something because I am a grammar nazi and that phrase
bothers me.
THE RUNDOWN
• Type: Behavioral
• Good For: Notifying observer objects that a particular subject's state has
changed.
• Example Code: On GitHub
THE PARTICIPANTS
• The Subject knows its Observers and provides an interface for attaching or
detaching any number of Observer objects.
Page 44
Matthew P Jones The Daily Design Pattern
A DELICIOUS EXAMPLE
To model the Observer design pattern, let's imagine that we need a system to model
the fluctuating prices of vegetables at our local market (e.g. a stock market, but for
vegetables).
First, let’s define our Subject participant as an abstract class, which needs to
implement methods by which it can attach or detach observers and keeps track of a
certain Veggie's current price:
Page 45
Matthew P Jones The Daily Design Pattern
Console.WriteLine("");
}
Page 46
Matthew P Jones The Daily Design Pattern
// ConcreteSubject
class Carrots : Veggies
{
public Carrots(double price) : base(price) { }
}
Now we can define our Observer participant. Remember that restaurants want to
observe the vegetable prices, so our Observer will naturally be an
interface IRestaurant, and this interface must define a method by which its
implementors can be updated:
Page 47
Matthew P Jones The Daily Design Pattern
Note that the Restaurants will want to buy veggies if the price dips below a certain
threshold amount, which differs per restaurant.
Page 48
Matthew P Jones The Daily Design Pattern
To put this all together, in our Main method in the Program.cs file we can define a
few restaurants that want to observe the price of carrots, then fluctuate that price:
Console.ReadKey();
}
If we run the app, we see that as the price changes, the restaurants get notified, and
if the price drops below each restaurant's threshold, that restaurant then wants to
place an order. Here's a sample output:
As we can see, the subject object (Carrots) automatically notifies the observer
restaurants of its own
price changes, which can
then decide what to do
with that information
(e.g. place an order for
more carrots).
(Dang. So close!)
Page 49
Matthew P Jones The Daily Design Pattern
sure you aren't forcing the Observer design pattern into a solution where it doesn't
solve the problem it is intended to solve.
SUMMARY
The Observer design pattern seeks to allow Observer objects to automatically receive
notifications (and possibly change their own state) when a Subject class changes its
state. In short, should the Subject change its own state, the Observers will know
about that change.
The purpose of this pattern is to separate the current state of the object from a
previous state, so that if something happens to the current state (it gets corrupted,
it gets lost, it tries to secede from the Union) the object's state can be restored from
its Memento (whether via a civil war or other, less interesting methods).
For example, let’s create a memento of my current state when writing this chapter:
hungry.
Now we can use that memento later to restore the state of the someBlogger object.
THE RUNDOWN
• Type: Behavioral
• Good For: Restoring an object's state from a previous state by creating a
memento of said previous state.
• Example Code: On GitHub
Page 50
Matthew P Jones The Daily Design Pattern
THE PARTICIPANTS
• The Memento stores internal state of the Originator object. The Memento has
no limit on what it may
or may not store (e.g. as
much or as little of the
Originator's state as
needed).
• The Originator creates
a Memento containing a
"snapshot" of its internal
state, and then later uses that memento to restore its internal state.
• The Caretaker is responsible for the Memento's safekeeping, but does not
operate on or examine the contents of that Memento.
A DELICIOUS EXAMPLE
Well, in so far as "delicious" means "fitting the food theme" anyway.
Let's imagine a system in which a restaurant needs to record information about the
suppliers that bring them their ingredients. For example, a really high-end restaurant
might order directly from
a local farm, and the
restaurant needs to keep
track of which ingredients
come from which
suppliers.
Page 51
Matthew P Jones The Daily Design Pattern
First, let’s create our Originator participant, which we will call FoodSupplier, and
has the following properties:
class FoodSupplier
{
private string _name;
private string _phone;
private string _address;
//...
}
Page 52
Matthew P Jones The Daily Design Pattern
This class also needs methods by which it can create and use Mementos:
// Originator
class FoodSupplier
{
// ...
With the Originator created, we now need to make a Memento participant. This class
will represent the state of the object that needs to be restored.
Page 53
Matthew P Jones The Daily Design Pattern
Finally, we need our Caretaker participant, which stores the Mementos but never
inspects or modifies them.
// Caretaker
class SupplierMemory
{
private FoodSupplierMemento _memento;
In our Main method, we can simulate adding a new Supplier but accidentally adding
the wrong address, then using the Memento to restore the old data:
Console.ReadKey();
}
Page 54
Matthew P Jones The Daily Design Pattern
come up with real-world situations where this pattern is necessary. If you, dear
reader, have ever used this pattern in a real situation, please let me know!
SUMMARY
The Memento design pattern seeks to encapsulate state of an object as another
object (called a Memento) and enable the ability to restore the state of the
object from that Memento.
someBlogger.FinishWriting();
someBlogger.RestoreState(memento); //Hungry again!
The typical way of thinking about this pattern is to consider how we might model the
color spectrum. There are something like 10 million visible colors, so modeling them
as individual classes (e.g. Red, LightMauve, MacaroniAndCheese, Octarine) would
be rather impractical.
However, a color is a color, no matter what color it is; colors have the same kinds of
properties as each other even if they don't have the same values for those properties.
If we needed to create a lot of color instances, we could do so using the Prototype
design pattern.
This being the Daily Design Pattern, though, we aren’t going to model this pattern
with colors.
THE RUNDOWN
• Type: Creational
• Good For: Creating lots of similar objects.
• Example Code: On GitHub
THE PARTICIPANTS
• The Prototype declares an interface for cloning itself.
Page 55
Matthew P Jones The Daily Design Pattern
A DELICIOUS EXAMPLE
Just like we did for Day 1’s Factory
Method Pattern and Day 2’s Abstract
Factory Pattern, we’re going to use
sandwiches to model the Prototype
pattern.
Now we need the ConcretePrototype participant class that can clone itself to create
more Sandwich instances. For our model, we'll say that a Sandwich consists of four
parts: the meat, cheese, bread, and veggies. Here's that class:
Page 56
Matthew P Jones The Daily Design Pattern
Page 57
Matthew P Jones The Daily Design Pattern
We also need another class which stores a collection of sandwich prototypes, from
which we will create our many instances.
class SandwichMenu
{
private Dictionary<string, SandwichPrototype> _sandwiches
= new Dictionary<string, SandwichPrototype>();
In our Main() method (which does double-duty as our Client participant), we can do
just that by instantiating the prototype and then cloning it, thereby populating our
SandwichMenu collection. The example code for this is on the next page.
Page 58
Matthew P Jones The Daily Design Pattern
class Program
{
static void Main(string[] args)
{
SandwichMenu sandwichMenu = new SandwichMenu();
By the time we get to the line Console.ReadKey(), how many total separate
instances of Sandwich do we have? Nine, six in the sandwichMenu and three
initialized as variables sandwich1, sandwich2, sandwich3.
Page 59
Matthew P Jones The Daily Design Pattern
The situation in which I see this pattern as being the most useful is when all of the
following happens:
If you have all of those conditions, the Prototype design pattern is for you!
SUMMARY
The Prototype pattern initializes objects by cloning them from a prototypical instance
of said object. It's especially useful when you need to create many instances of
related items, each of which could be slightly (but not very) different from the other
instances.
The primary benefit of this pattern is reduced initialization costs; by cloning many
instances from a prototypical instance, you theoretically improve performance.
What this means is that the pattern forces a particular object to not have an
accessible constructor, and that any access performed on the object is performed
upon the same instance of that object.
As you may have heard, Singleton is one of the most maligned design patterns (for
reasons we will discuss below).
THE RUNDOWN
• Type: Creational
• Good For: Creating an object of which there can only ever be one.
• Example Code: On GitHub
THE PARTICIPANTS
It’s kind of silly to define participants for this very simple pattern, but here we go:
Page 60
Matthew P Jones The Daily Design Pattern
A DELICIOUS EXAMPLE
The theme I've been using for this book so far is "food", but food items are not a
good way to model Singleton: there's not ever going to be a piece of food that
everybody will access a single instance of (because that would be gross). Instead,
let's visit our local diner and think about that little bell that sits on the counter.
Page 61
Matthew P Jones The Daily Design Pattern
/// Singleton
public sealed class TheBell
{
private static TheBell bellConnection;
private static object syncRoot = new Object();
private TheBell() { }
public static TheBell Instance
{
get
{
lock(syncRoot)
{
if(bellConnection == null)
bellConnection = new TheBell();
}
return bellConnection;
}
}
Notice that the TheBell class has a private constructor. This is to ensure that it can
never be instantiated, and can only be accessed through the Instance property.
Further, note the syncRoot object. This a simple object that allows our Singleton to
be thread-safe; since there's only ever one, we must ensure that any thread which
wants to access it has an exclusive lock on it.
For one thing, Singletons are not global variables, though the latter is often mistaken
for the former. A Singleton is a class unto itself, and global variables are just
properties.
Further, many people argue that Singletons violate common guiding principles such
as the Single Responsibility Principle. By its very nature, you cannot pass a Singleton
Page 62
Matthew P Jones The Daily Design Pattern
to other classes, and this is often a code smell, an indication of something that should
be fixed or refactored.
Mostly, though, Singletons are maligned because they are so often misused. It's
entirely too easy, to paraphrase Jamie Zawinski, to see a problem, think "I know, I'll
use a Singleton," and now they have two problems. Be careful that what you're using
the Singleton for actually requires that pattern, and even then, be on the lookout for
a better, more appropriate manner by which you can solve your current problem.
Thing is, Singletons are (fittingly) good for one and only one purpose yet are easily
understood and quick to implement, which makes them a favorite of people afflicted
with golden hammer syndrome. It's all too common to find Singletons in use where
global variables should be used instead.
All patterns are designed to solve a specific set of problems. But Singleton is very,
very simple for a very, very common use case, and thus is prone to being used in
places where it’s not a good fit.
Use the Singleton design pattern sparingly and only for its intended purpose (a single,
globally accessible instance of an object) with full knowledge of this pattern's limits,
and you'll find that it, like all the other design patterns, has its own set of valid uses.
SUMMARY
Singletons are objects of which there can only ever be exactly one instance. They're
not global variables and many people think they violate common principles of good
software development, but they do have their uses and so should be used sparingly.
• The intrinsic state, which is stored within the Flyweight object itself, and
• The extrinsic state, which is stored or calculated by other components.
The Flyweight design pattern allows many instances of an object to share their
intrinsic state and thereby reduce the cost associated with creating them.
Page 63
Matthew P Jones The Daily Design Pattern
THE RUNDOWN
• Type: Structural
• Good For: Creating lots of instances of the same set of objects and thereby
improving performance.
• Example Code: On GitHub
THE PARTICIPANTS
• The Flyweight declares an interface through which flyweights can receive and
act upon extrinsic state.
• The ConcreteFlyweight objects implement the Flyweight interface and may
be sharable. Any state stored by these objects must be intrinsic to the object.
• The FlyweightFactory creates and manages flyweight objects, while also
ensuring that they are shared properly. When the FlyweightFactory is asked to
create an object, it either uses an existing instance of that object or creates a
new one if no existing one exists.
• The Client maintains a reference to flyweights and computes or stores the
extrinsic state of said flyweights.
Page 64
Matthew P Jones The Daily Design Pattern
A DELICIOUS EXAMPLE
To model the Flyweight design pattern, let’s think about sliders.
For those of
you who might
not be familiar
with the term
"slider" when it
relates to
hamburgers, a
slider is a small
burger,
typically only 3
or 4 inches in
diameter.
They're often
used as party
snacks, but can
also be a meal
unto
themselves.
At any rate,
PHOTO BY EATERS COLLECTIVE / UNSPLASH let's imagine
that we need to
create a whole bunch of these sliders for our fictional restaurant; this is a good model
for Flyweight.
The Slider class has properties for Name, Cheese, Toppings, and Price (all of which
are part of the intrinsic state of these objects), and an abstract
method Display() which will display the details of that slider.
Page 65
Matthew P Jones The Daily Design Pattern
Now we need our ConcreteFlyweight objects. We’re going to build three of them,
each for a different type of slider. First, let’s build a class for a BaconMaster type
slider:
// A ConcreteFlyweight class
class BaconMaster : Slider
{
public BaconMaster()
{
Name = "Bacon Master";
Cheese = "American";
Toppings = "lots of bacon";
Price = 2.39m;
}
Page 66
Matthew P Jones The Daily Design Pattern
We’ll probably have some people who don’t like meat, so we’ll also need a veggie
slider:
// A ConcreteFlyweight class
class VeggieSlider : Slider
{
public VeggieSlider()
{
Name = "Veggie Slider";
Cheese = "Swiss";
Toppings = "lettuce, onion, tomato, and pickles";
Price = 1.99m;
}
Next, mostly because I like barbecue, we’re going to have a BBQ-style slider, the
example code for which is on the next page.
Note that the ConcreteFlyweight classes are, of course, very similar to one another:
they all have the same properties. This is critical to using Flyweight: all of the related
objects must have the same definition (or at least reasonably close to the same
definition).
Page 67
Matthew P Jones The Daily Design Pattern
// A ConcreteFlyweight class
class BBQKing : Slider
{
public BBQKing()
{
Name = "BBQ King";
Cheese = "American";
Toppings = "Onion rings, lettuce, and BBQ sauce";
Price = 2.49m;
}
Page 68
Matthew P Jones The Daily Design Pattern
Page 69
Matthew P Jones The Daily Design Pattern
When we run the app, we enter as many of those characters as we like to order as
many sliders as we like.
Looking at the screenshot above, the FlyweightFactory will have only created new
sliders for orders 1, 3, and 4, with every other order being a copy of those objects.
This is the power of Flyweight: you can theoretically improve performance by only
instantiating new objects on first creation.
Page 70
Matthew P Jones The Daily Design Pattern
In my opinion, if you need to create lots of instances of an object, you'd be better off
using something like the Prototype design pattern from Day 10 rather than Flyweight.
SUMMARY
The Flyweight pattern strives to improve performance by creating lots of objects from
a small set of "template" objects, where those objects are the same or very similar
to all their other instances. In practice, though, the usefulness of this pattern is
limited, and you might be better off using Prototype. That said, if anyone has a
different opinion on the benefits of Flyweight, I'd love to hear about it!
The general idea is that the order in which things happen when an object is
instantiated will be the same, but the actual details of those steps change based upon
what the concrete implementation is.
THE RUNDOWN
• Type: Creational
• Good For: Creating objects which need several steps to happen in order, but
the steps are different for different specific implementations.
• Example Code: On GitHub
THE PARTICIPANTS
• The Builder specifies an abstract interface for creating parts of a Product.
Page 71
Matthew P Jones The Daily Design Pattern
A DELICIOUS EXAMPLE
To demonstrate how the Builder
design pattern works, we once again
turn our hungry eyes to that most
portable and simple of lunch foods:
the humble sandwich.
Page 72
Matthew P Jones The Daily Design Pattern
// The Director
class AssemblyLine
{
// Builder uses a complex series of steps
public void Assemble(SandwichBuilder sandwichBuilder)
{
sandwichBuilder.AddBread();
sandwichBuilder.AddMeats();
sandwichBuilder.AddCheese();
sandwichBuilder.AddVeggies();
sandwichBuilder.AddCondiments();
}
}
We also need to define the Product participant which is being built by the Builder
participant. For this demo, the Product is, of course, a Sandwich.
class Sandwich
{
private string _sandwichType;
private Dictionary<string, string> _ingredients
= new Dictionary<string, string>();
Page 73
Matthew P Jones The Daily Design Pattern
Now that we know the definition of the product we are building, let's now create
the Builder participant - an abstract class SandwichBuilder:
Notice the five abstract methods. Each subclass of SandwichBuilder will need to
implement those methods in order to properly build a sandwich.
Page 74
Matthew P Jones The Daily Design Pattern
// A ConcreteBuilder class
class TurkeyClub : SandwichBuilder
{
public TurkeyClub()
{
sandwich = new Sandwich("Turkey Club");
}
Page 75
Matthew P Jones The Daily Design Pattern
// A ConcreteBuilder class
class BLT : SandwichBuilder
{
public BLT()
{
sandwich = new Sandwich("BLT");
}
Page 76
Matthew P Jones The Daily Design Pattern
// A ConcreteBuilder class
class HamAndCheese : SandwichBuilder
{
public HamAndCheese()
{
sandwich = new Sandwich("Ham and Cheese");
}
Note the similarities between the three implementations. Since we’ve defined all
sandwiches to be comprised of five parts (bread, meat, cheese, veggies, condiments)
each ConcreteBuilder needs to implement a method for each part.
Page 77
Matthew P Jones The Daily Design Pattern
Once we have all the ConcreteBuilder classes written up, we can use them in
our Main() like so:
The nice thing about this pattern is that we can now reuse the AssemblyLine class
on any SandwichBuilder we wish, and we have more fine-grained control over how
the sandwiches are built.
Page 78
Matthew P Jones The Daily Design Pattern
SUMMARY
The Builder pattern allows us to build related sets of objects with the same steps, but
leaving the implementation of those steps up to the subclasses. It's not terribly useful
as far as I can see, but as always I love being shown better ways to do things I didn’t
think could be done, so if you’ve seen a good candidate for the Builder design pattern
let me know!
The State design pattern seeks to allow an object to change its own behavior when
its internal state changes.
In this pattern, the "states" in which an object can exist are classes unto
themselves, which refer back to the object instance and cause that instance's
behaviors to differ depending on the state it is currently residing in.
THE RUNDOWN
• Type: Behavioral
• Good For: Allowing an object's behavior to change as its internal state does.
• Example Code: On GitHub
THE PARTICIPANTS
• The Context defines an interface of interest to the clients. It also maintains a
reference to an instance of ConcreteState which represents the current state.
• The State defines an interface for encapsulating the behavior of the object
associated with a particular state.
• The ConcreteState objects are subclasses which each implement a behavior
(or set of behaviors)
associated with a state
of the Context.
Page 79
Matthew P Jones The Daily Design Pattern
A DELICIOUS EXAMPLE
Those of you who don't like red meat, turn back now. For everyone else, let's talk
about steaks; specifically, how to cook them to different temperatures.
The United States Food and Drug Administration sets guidelines as to how thoroughly
cooked a steak must be
in order to be a) safe to
eat, and b) considered a
certain level of
"doneness" (which is
rapidly becoming my
new favorite word). For
many steaks, the levels
of doneness are:
• Uncooked (not
safe to eat)
• Rare
• Medium-Rare
(mid-rare)
• Medium
PHOTO BY EMERSON VIEIRA / UNSPLASH
• Medium-Well
(mid-well)
• Well done
Let's implement a system which keeps track of the internal temperature of a steak
and assigns a level of doneness to it. We can model this using the State design
pattern.
Page 80
Matthew P Jones The Daily Design Pattern
First, let's define our State participant, which represents a "doneness" level for a
steak (and maintains a reference to an actual Steak instance).
Now that we have the State participant, let's define some ConcreteState objects.
First, let's define a state for when the steak is uncooked and, therefore, not safe to
eat. In this state, we can add cook temperature and remove cook temperature, but
the steak will not be safe to eat until the cook temp is above 130 degrees Fahrenheit
(54.4 degrees Celsius).
Page 81
Matthew P Jones The Daily Design Pattern
Page 82
Matthew P Jones The Daily Design Pattern
Now let's discuss the first edible state, Rare. In this state, we can add and remove
cook temperature, and the steak is now edible (so we must initialize it as such).
// A 'ConcreteState' class.
class Rare : Doneness
{
public Rare(Doneness state) : this(state.CurrentTemp, state.Steak) { }
Page 83
Matthew P Jones The Daily Design Pattern
Page 84
Matthew P Jones The Daily Design Pattern
Page 85
Matthew P Jones The Daily Design Pattern
Now that we have all of our states defined, we can finally implement
our Context participant. In this case, the Context is a Steak class which maintains
a reference to the Doneness state it is currently in. Further, whenever we add or
remove temperature from the steak, it must call the current Doneness state's
corresponding method.
Page 86
Matthew P Jones The Daily Design Pattern
Page 87
Matthew P Jones The Daily Design Pattern
In our Main() method, we can use these states by creating a Steak object and then
changing its internal temperature:
Console.ReadKey();
}
Page 88
Matthew P Jones The Daily Design Pattern
SUMMARY
The State pattern allows the behavior
of an object to change as its internal
state changes, and it accomplishes this
by making the states of an object separate classes from the object itself.
Consequently, the states can implement their own behavior for the object, and the
object can "react" to its internal state changing.
Page 89
Matthew P Jones The Daily Design Pattern
The Strategy design pattern defines a family of algorithms, then makes them
interchangeable by encapsulating each as an object. Consequently, the actual
operation of the algorithm can vary based on other inputs, such as which client is
using it.
The basic idea of this pattern is that if we encapsulate behavior as objects, we can
then select which object to use and, thereby, which behavior to implement based
upon some external inputs or state. We further allow for many different behaviors to
be implemented without creating huge if/then or switch statements.
THE RUNDOWN
• Type: Behavioral
• Good For: Encapsulating parts of an algorithm as objects and allowing them
to be invoked independently.
• Example Code: On GitHub
THE PARTICIPANTS
• The Strategy declares an interface which is implemented by all supported
algorithms.
• The ConcreteStrategy objects implement the algorithm defined by the
Strategy.
• The Context maintains a
reference to a Strategy
object, and uses that
reference to call the
algorithm defined by a
particular
ConcreteStrategy.
Page 90
Matthew P Jones The Daily Design Pattern
A DELICIOUS EXAMPLE
To model this pattern, let's talk about some different ways to cook food.
/// The Strategy abstract class, which defines an interface common to all
supported strategy algorithms.
abstract class CookStrategy
{
public abstract void Cook(string food);
}
Each strategy by which we will cook a food item must implement the method Cook().
Let's implement a few of those strategies now (these are all ConcreteStrategy
participants):
Page 91
Matthew P Jones The Daily Design Pattern
Page 92
Matthew P Jones The Daily Design Pattern
To complete the demo app, let's implement our Context participant, which maintains
a reference to both the food we are cooking and the Strategy we are using to do so:
Page 93
Matthew P Jones The Daily Design Pattern
Finally, we can allow the user to select what food they want to cook and what Strategy
they wish to use in our Main() (example on next page).
switch(input)
{
case 1:
cookMethod.SetCookStrategy(new Grilling());
cookMethod.Cook();
break;
case 2:
cookMethod.SetCookStrategy(new OvenBaking());
cookMethod.Cook();
break;
case 3:
cookMethod.SetCookStrategy(new DeepFrying());
cookMethod.Cook();
break;
default:
Console.WriteLine("Invalid Selection!");
break;
}
Console.ReadKey();
}
We can now demonstrate how the Strategy pattern works by cooking some food.
Let's say we want to cook pork chops. The next three screenshots show the sample
program output for cooking pork chops three different ways:
Page 94
Matthew P Jones The Daily Design Pattern
Ta-da! We now have a working model of the Strategy design pattern! But, you know,
this pattern looks very similar to the State design pattern we demoed on Day 14.
Page 95
Matthew P Jones The Daily Design Pattern
STRATEGY VS STATE
It's worthwhile to note that the Strategy design pattern and the State design
pattern are indeed similar, but are used in different ways.
SUMMARY
The Strategy design pattern allows different behaviors for a given object to be used
under different circumstances. This allows for many different behaviors to be
implemented and tested separately, since each will be encapsulated as an object.
Now to find out exactly how many ways there are to cook pork chops. Mmmmmm.
This Proxy object can then hide or change data on the hidden object, or otherwise
manipulate its behavior. However, the Proxy must still be able to be used anywhere
the hidden object is.
THE RUNDOWN
• Type: Structural
• Good For: Controlling access to a particular object, testing scenarios.
Page 96
Matthew P Jones The Daily Design Pattern
THE PARTICIPANTS
• The Subject defines a common interface for the RealSubject and the Proxy
such that the Proxy can be used anywhere the RealSubject is expected.
• The RealSubject defines the
concrete object which the Proxy
represents.
• The Proxy maintains a reference
to the RealSubject and controls
access to it. It must implement the
same interface as the RealSubject
so that the two can be used
interchangeably.
A DELICIOUS EXAMPLE
Similarly to what we
did on Day 3 with the
Façade design pattern,
let’s talk about servers
in a high-end
restaurant to model
what we can do with
the Proxy design
pattern.
In addition to being a
layer of abstraction
between the patrons
and the kitchens,
servers also have tasks
to perform. For this
day’s example, let's
imagine that servers at a restaurant primarily do three things:
Page 97
Matthew P Jones The Daily Design Pattern
With these assumptions, we can create an interface for these actions (this interface
being the Subject participant):
// Subject interface which the RealSubject and proxy will need to implement
public interface IServer
{
void TakeOrder(string order);
string DeliverOrder();
void ProcessPayment(string payment);
}
Now imagine for a second that one of our Server instances is an experienced
employee of this restaurant who is helping train a newly-hired server. That new hire,
from the patron's perspective, is still a server and should still behave as such.
However, the new trainee cannot process payments yet, as he must first learn the
ropes of taking and delivering orders.
Page 98
Matthew P Jones The Daily Design Pattern
We can create a Proxy to model this new employee. The Proxy will need to maintain
a reference back to the Server instance so that it can call
the Server instance's ProcessPayment() method:
// The Proxy class, which can substitute for the Real Subject.
class NewServerProxy : IServer
{
private string Order;
private Server _server = new Server();
Page 99
Matthew P Jones The Daily Design Pattern
SUMMARY
The Proxy pattern seeks to create a "stand-in" object which can be used in place of
an existing object and maintains a reference to an instance of said existing object.
To fulfill the pattern, the Proxy object must be able to be used anywhere the replaced
object can be used.
Oh, and while you're here, check out our wine specials. There's sure to be something
to suit your taste.
The Decorator design pattern seeks to add new functionality to an existing object
without changing that object's definition.
THE RUNDOWN
• Type: Structural
• Good For: Injecting new functionality into instances of objects at runtime
rather than including that functionality in the class of objects.
• Example Code: On GitHub
THE PARTICIPANTS
• The Component defines the
interface for objects which will have
responsibilities or abilities added to
them dynamically.
• The ConcreteComponent objects
are objects to which said
responsibilities are added.
• The Decorator maintains a
reference to a Component and
defines and interface that conforms
to the Component interface.
• The ConcreteDecorator objects
are the classes which actually add responsibilities to the ConcreteComponent
classes.
Page 100
Matthew P Jones The Daily Design Pattern
A DELICIOUS EXAMPLE
In keeping with the restaurant and food theme we’ve been using for our examples,
let’s demonstrate how we might use the Decorator design pattern to model a farm-
to-table style restaurant.
To model this farm-to-table restaurant, let's first define our Component participant,
which is a RestaurantDish abstract class:
Page 101
Matthew P Jones The Daily Design Pattern
// A ConcreteComponent class
class FreshSalad : RestaurantDish
{
private string _greens;
private string _cheese; //I’m going to use this pun everywhere
private string _dressing;
// A ConcreteComponent class
class Pasta : RestaurantDish
{
private string _pastaType;
private string _sauce;
We need to decorate those dishes at runtime with the ability to keep track of whether
or not we've exhausted all the ingredients. To do this, let's first implement
a Decorator abstract class (which, in a rare case of name matching purpose, is also
our Decorator participant):
Page 102
Matthew P Jones The Daily Design Pattern
Page 103
Matthew P Jones The Daily Design Pattern
Finally, we need a ConcreteDecorator for keeping track of how many of the dishes
have been ordered. The example code for this participant is on the next page.
Like many of the other design patterns in this book, all of this setup comes to fruition
in the Main() method in our Program.cs file.
In that method, we define a set of dishes, then we decorate those dishes so that
when we run out of ingredients we can notify the patron. Finally, we order those
dishes. The complete main method looks like the example on the next page.
Page 104
Matthew P Jones The Daily Design Pattern
//Step 2: Decorate the dishes; now if we attempt to order them once we're
out of ingredients, we can notify the customer
Available caesarAvailable = new Available(caesarSalad, 3);
Available alfredoAvailable = new Available(fettuccineAlfredo, 4);
alfredoAvailable.OrderItem("Sally");
alfredoAvailable.OrderItem("Francis");
alfredoAvailable.OrderItem("Venkat");
alfredoAvailable.OrderItem("Diana");
alfredoAvailable.OrderItem("Dennis");//There won't be enough for this one
caesarAvailable.Display();
alfredoAvailable.Display();
Console.ReadKey();
}
When we run the app, the output looks like the screenshot on the next page. As you
can see, Dennis can't order the fettuccine alfredo because we've run out of
Page 105
Matthew P Jones The Daily Design Pattern
SUMMARY
The Decorator pattern seeks to dynamically add functionality to instances of objects
at runtime, without
needing to change the
definition of the instance's
class. This is especially
useful in scenarios where
different instances of the
same object might behave
differently (such as dishes
in a restaurant or items in
a library).
Page 106
Matthew P Jones The Daily Design Pattern
In essence, we pass an object along a "chain" of potential handlers for that object
until one of the handlers deals with the request.
THE RUNDOWN
• Type: Behavioral
• Good For: Allowing multiple different objects to decide whether or not to
process or modify a request.
• Example Code: On GitHub
THE PARTICIPANTS
• The Handler defines an interface for handling requests.
• The ConcreteHandler objects can each handle a request, and can access
their successor object.
• The Client initiates
the request to a
ConcreteHandler
object.
A DELICIOUS EXAMPLE
Let’s continue the
restaurant theme from
Day 16 and Day 17 and discuss what a restaurant needs to operate. Specifically,
we’re going to try to model the chain of command that allows a restaurant (or, really,
any business) to get new equipment.
In a given restaurant, there is most likely a hierarchy in which the people who work
at that establishment are placed. When a kitchen needs supplies, the Head Chef of
that kitchen is likely to be the first one to notice. So, s/he might need to file a
purchase request with his/her bosses in order to obtain new equipment, such as
knives or cutting boards or even larger items like ovens.
In our demo kitchen specifically, the purchase request system operates like this:
Page 107
Matthew P Jones The Daily Design Pattern
1. The Head Chef has implicit approval to purchase any item which is less than
$1000 USD.
2. If the total amount of the purchase is greater than that but less than $2500,
the Head Chef must get the restaurant's Purchasing Manager's approval for
the purchase.
3. If the total amount of the purchase is greater than $2500 but less than $10000,
then the head chef must get the approval of the restaurant's General Manager
to make the purchase.
4. Finally, if the purchase amount is greater than $10000, the General Manager
will call an executive meeting to determine if they need to make the purchase
requested.
Page 108
Matthew P Jones The Daily Design Pattern
With that in place, we can now write an abstract class Approver which is
our Handler participant. This represents any person in the chain who can approve
requests.
// The Handler abstract class. Every class which inherits from this will be
// responsible for a kind of request for the restaurant.
abstract class Approver
{
protected Approver Supervisor;
Now we can implement our ConcreteHandler objects: one for each person in the
chain.
Page 109
Matthew P Jones The Daily Design Pattern
Notice that each person in the hierarchy (e.g. each link in the chain) can call its own
supervisor to make a determination as to whether or not the item can be purchased.
This is part of the Chain of Responsibility design pattern: each link is aware of its own
successor.
Page 110
Matthew P Jones The Daily Design Pattern
Finally, we need a Client participant, which in this case is our Main() method in the
Program.cs file.
Notice that all requests initially flow to Jennifer, the head chef, but if the request's
total price is greater than certain amounts then the requests automatically flow to
Mitchell the purchasing
manager or Olivia the
general manager.
Page 111
Matthew P Jones The Daily Design Pattern
SUMMARY
The Chain of Responsibility pattern allows for multiple objects in a chain to make a
pass at handling a request object. The request flows through the chain until a link in
the chain handles it.
Now I need to go have a talk with Olivia. She never approves my requests. Just
because I burnt all the sausages last week doesn't mean I don't need that automatic
donut making machine I asked for! I mean, look at it! It's beautiful!
This pattern is particularly useful when, for one reason or another, we cannot modify
or refactor existing classes but need to change their behavior.
THE RUNDOWN
• Type: Behavioral
• Good For: Operating on objects without changing their classes.
• Example Code: On GitHub
THE PARTICIPANTS
• The Visitor declares an operation for each of ConcreteElement in the object
structure.
• The ConcreteVisitor implements each operation defined by the Visitor. Each
operation implements a fragment of the algorithm needed for that object.
• The Element defines an Accept operation which takes a Visitor as an
argument.
• The ConcreteElement implements the Accept operat ion defined by the
Element.
Page 112
Matthew P Jones The Daily Design Pattern
A DELICIOUS EXAMPLE
To model the Visitor design pattern,
let's talk about a very successful
restaurant and the employees who
work there.
Upper management has decided that it's time to reward our hard-working employees
by giving them raises and extra time off. Problem is, the classes which represent our
employees (stay with me here) are already created and, for whatever reason, cannot
be changed.
We first need C# classes to represent the employees of the restaurant. This first
example is our Element participant. Said class will need to implement a method to
accept a Visitor object, and also need to be implementable by other objects; hence
we define it as an abstract class.
// The Element abstract class. All this does is define an Accept operation,
which needs to be implemented by any class that can be visited.
abstract class Element
{
public abstract void Accept(IVisitor visitor);
}
Page 113
Matthew P Jones The Daily Design Pattern
We also will define our ConcreteElement participant, which represents the employees
of our restaurant, and implement the Element abstract class.
With the classes for our employees defined, we now need to implement the actual
Visitor participant which will “visit” these employee records and modify both their
salary and paid time off accordingly.
Page 114
Matthew P Jones The Daily Design Pattern
Now we need our ConcreteVisitor participants, one for each detail about the
employee records that we want to change.
// And because you all helped have such a great year, all
// employees get three extra paid time off days each!
employee.PaidTimeOffDays += 3;
Console.WriteLine("{0} {1}'s new vacation days: {2}",
employee.GetType().Name, employee.Name, employee.PaidTimeOffDays);
}
}
When those visitor participants “visit” the employee records, they will update them
accordingly.
Page 115
Matthew P Jones The Daily Design Pattern
class Employees
{
private List<Employee> _employees = new List<Employee>();
Page 116
Matthew P Jones The Daily Design Pattern
All that’s left to do is run the sample app. When we do so, we will create a new
collection of employees and send visitors to modify their salary and paid time off
records. It looks like this:
Console.ReadKey();
}
Further, it appears that more recent versions of C# might actually negate the need
to use this pattern in certain scenarios in the first place. Again, I don't have a lot of
first-hand experience with this pattern, but if you think it will help you and your
projects, might as well give it a go.
Page 117
Matthew P Jones The Daily Design Pattern
SUMMARY
The Visitor pattern allows us to modify existing instances of objects without modifying
the class they are a part of. All those instances need to do is accept a Visitor object
and process its contents. That said, this pattern (in my opinion) provides more
complexity than value and shouldn't be used extensively.
The next pattern we are going to demo is one that can make a complicated hierarchy
structure much simpler to implement: Composite.
When using this pattern, clients should be able to treat groups of objects in a
hierarchy as "the same" even though they can be different. You can do this selectively
to parts of the hierarchy, or to the entire hierarchy.
I know this sounds complex, but it really isn’t too bad. Let’s see how to use the
Composite design pattern!
THE RUNDOWN
• Type: Structural
• Good For: Treating distinct objects in a related hierarchy as the same kind of
object.
• Example Code: On GitHub
THE PARTICIPANTS
• The Component declares an interface for objects in the composition. It also
implements behavior that is common to all objects in said composition. Finally,
it must implement an interface for adding/removing it's own child components.
• The Leaves represent leaf behavior in the composition (a leaf is an object with
no children). It also defines primitive behavior for said objects.
Page 118
Matthew P Jones The Daily Design Pattern
A DELICIOUS EXAMPLE
To model the Composite design pattern effectively, let’s think about a soda dispenser.
More specifically, one of the Coca-Cola Freestyle machines you’ll find at certain
restaurants or movie theatres.
Page 119
Matthew P Jones The Daily Design Pattern
We’re going to model this hierarchy using the Composite design pattern. We’re also
going to introduce a wrinkle: for all possible flavors of soda that our machine
dispenses, we need to know how many calories each particular flavor has. We can
thereby create an abstract class that represents all soft drinks, which in turn has a
property for Calories.
Note the DisplayCalories() method in the example code on the next page. This is
a recursive method that will show the calories for all nodes, starting from the current
node. We will use this method a bit later to output all calories for all drinks.
Page 120
Matthew P Jones The Daily Design Pattern
Next up, we need to implement several Leaves for the concrete soda flavors:
// Leaf class
public class VanillaCola : SoftDrink
{
public VanillaCola(int calories) : base(calories) { }
}
// Leaf class
public class CherryCola : SoftDrink
{
public CherryCola(int calories) : base(calories) { }
}
// Leaf class
public class StrawberryRootBeer : SoftDrink
{
public StrawberryRootBeer(int calories) : base(calories) { }
}
Page 121
Matthew P Jones The Daily Design Pattern
// Leaf class
public class VanillaRootBeer : SoftDrink
{
public VanillaRootBeer(int calories) : base(calories) { }
}
// Leaf class
public class LemonLime : SoftDrink
{
public LemonLime(int calories) : base(calories) { }
}
If strawberry root beer isn’t already a thing, I would definitely like it to be.
// Composite class
public class Cola : SoftDrink
{
public Cola(int calories) : base(calories) { }
}
// Composite class
public class RootBeer : SoftDrink
{
public RootBeer(int calories) : base(calories) { }
}
Note that the Composite classes don’t look all that different from the Leaf classes.
The only real difference between them is that Composites are expected to have
“child” nodes in the hierarchy, whereas Leaf classes will not have child nodes.
Page 122
Matthew P Jones The Daily Design Pattern
Lastly, we need an additional composite class for the root node. In our diagram, the
root node is soda water.
The only part left to do is the implementation of our Main() method in the Program.cs
file. This example shows how we might initialize a soft drink hierarchy with several
flavors, and then display the calories for each flavor.
sodaWater.DisplayCalories();
Console.ReadKey();
}
Page 123
Matthew P Jones The Daily Design Pattern
SUMMARY
The Composite pattern takes objects in a hierarchy and allows clients to treat
different parts of that hierarchy as being the same. Then, among other things, you
can "flatten" all or part of the hierarchy to get only the data that's common to all of
the parts.
(For the international soda drinkers out there, maybe you can help me with
something. I was not aware that the flavor “root beer” was only a North American
thing, but Wikipedia says it is. Do you all not get this kind of soda in your country?
Because it is the bomb and you should try it.)
The Mediator design pattern defines an object which encapsulates how a set of
objects interact with each other.
THE RUNDOWN
• Type: Behavioral
• Good For: Defining how objects interact with each other.
• Example Code: On GitHub
Page 124
Matthew P Jones The Daily Design Pattern
THE PARTICIPANTS
• The Mediator defines an interface for communicating with Collegue objects.
• The Colleague classes each
know what Mediator is
responsible for them and
communicates with said
Mediator whenever it would
have otherwise communicated
directly with another
Colleague.
A DELICIOUS EXAMPLE
For this demo, let’s consider the snack bars at your local movie theatre.
Movie theatres,
relative to other
kinds of buildings,
tend to take up a lot
of ground space. A
particular cinema
that's not too far
from me has 25
screens spread out
over three different
"sections" of the
theatre. Each of
these sections,
being far enough
apart from each
other, has their own
PHOTO BY KRISTS LUHAERS / UNSPLASH snack bar, from
which we gluttonous
patrons can order salty snacks and sugary drinks to our heart content.
But selling concessions to hungry movie-goers requires supplies, and sometimes the
different snack bars might run out of said supplies. Let's imagine a system in which
the different concession stands can talk to each other, communicating what supplies
they need and who might have them (in short, a chat system for movie snack bars).
We can model this using the Mediator pattern.
Page 125
Matthew P Jones The Daily Design Pattern
First, we'll need our Mediator interface, which defines a method by which the snack
bars can talk to each other:
// The Mediator interface, which defines a send message method which the
// concrete mediators must implement.
interface Mediator
{
void SendMessage(string message, ConcessionStand concessionStand);
}
We also need an abstract class to represent the Colleagues that will be talking to
one another.
Page 126
Matthew P Jones The Daily Design Pattern
Note that each Colleague must be aware of the Mediator that is mediating the
colleague's messages.
Page 127
Matthew P Jones The Daily Design Pattern
Finally, we can implement the ConcreteMediator class, which will keep a reference
to each Colleague and manage communication between them.
// The Concrete Mediator class, which implements the send message method and
// keep track of all participants in the conversation.
class ConcessionsMediator : Mediator
{
private NorthConcessionStand _northConcessions;
private SouthConcessionStand _southConcessions;
Page 128
Matthew P Jones The Daily Design Pattern
In our Main() method, we can use our newly-written Mediator to simulate a chat
conversation between the two snack bars. Suppose that one of the snack bars has
run out of popcorn, and needs to know if the other has extra that they're not using:
mediator.NorthConcessions = leftKitchen;
mediator.SouthConcessions = rightKitchen;
rightKitchen.Send("Do you have any extra hot dogs? We've had a rush on
them over here.");
leftKitchen.Send("Just a couple, we'll send Kenny back with them.");
Console.ReadKey();
}
When we run this app, we’ll see a conversation between the two concessions stands.
Page 129
Matthew P Jones The Daily Design Pattern
SUMMARY
The Mediator pattern encapsulates an object which represents how other objects
communicate with one another. By doing so, it enables the Mediator to "stand
between" communicating objects and control their communications.
The Chain of Responsibility pattern from Day 18 fits well with the Command pattern,
as the former can use objects of the latter to represent its requests.
THE RUNDOWN
• Type: Behavioral
• Good For: Encapsulating requests as objects so that they can be processed
differently by different receivers.
• Example Code: On GitHub
THE PARTICIPANTS
• The Command declares an interface for executing an operation.
• The ConcreteCommand defines a binding between a Receiver and an action.
• The Client creates a
ConcreteCommand
object and sets its
receiver.
• The Invoker asks the
command to carry out
its request.
• The Receiver knows
how to perform the
operations associated
with carrying out the
request.
Page 130
Matthew P Jones The Daily Design Pattern
A DELICIOUS EXAMPLE
With this pattern in particular, merely defining the participants doesn’t do a good job
of explaining why we’d ever use the Command design pattern. Let’s build a sample
project to explain what this pattern does.
Page 131
Matthew P Jones The Daily Design Pattern
Since those items will be ordered by a patron of the restaurant, let's create
a Patron object which will also be our Invoker participant. It just so happens that
our implementation of the Invoker also includes an implementation of the Factory
Method Design Pattern from all the way back in Day 1:
public Patron()
{ _order = new FastFoodOrder(); }
Page 132
Matthew P Jones The Daily Design Pattern
// The Receiver
public class FastFoodOrder
{
public List<MenuItem> currentItems { get; set; }
public FastFoodOrder()
{
currentItems = new List<MenuItem>();
}
FastFoodOrder keeps track of all items in the order, so that when commands arrive
at it, it can process those commands using its own list of items.
Page 133
Matthew P Jones The Daily Design Pattern
// A concrete command
public class AddCommand : OrderCommand
{
public override void Execute(List<MenuItem> currentItems,
MenuItem newItem)
{
currentItems.Add(newItem);
}
}
// A concrete command
public class RemoveCommand : OrderCommand
{
public override void Execute(List<MenuItem> currentItems,
MenuItem newItem)
{
currentItems.Remove(currentItems
.Where(x=>x.Name == newItem.Name).First());
}
}
// A concrete command
public class ModifyCommand : OrderCommand
{
public override void Execute(List<MenuItem> currentItems,
MenuItem newItem)
{
var item = currentItems.Where(x => x.Name == newItem.Name).First();
item.Price = newItem.Price;
item.Amount = newItem.Amount;
}
}
With all the pieces in place, let’s create our Client participant. As in many of the
previous design pattern examples, the Client is really just our Main() method in the
Program.cs file.
The Client will create a ConcreteCommand object and set the receiver. In our
particular case, we will add several items to our patron’s order, then delete an item
and change another item. The example code is on the next page.
Page 134
Matthew P Jones The Daily Design Pattern
patron.SetCommand(1 /*Add*/);
patron.SetMenuItem(new MenuItem("Hamburger", 2, 2.59));
patron.ExecuteCommand();
patron.SetCommand(1 /*Add*/);
patron.SetMenuItem(new MenuItem("Drink", 2, 1.19));
patron.ExecuteCommand();
patron.ShowCurrentOrder();
patron.ShowCurrentOrder();
patron.ShowCurrentOrder();
Console.ReadKey();
}
As the orders are processed by the Receiver participant (the FastFoodOrder class),
the contents of the order changes. See the screenshot on the next page.
Page 135
Matthew P Jones The Daily Design Pattern
SUMMARY
The Command design pattern seeks to
encapsulate commands as objects and
allow different receivers to process them,
according to the receivers' own design.
With some setup, you can easily allow
classes to modify commands before they
are submitted to whatever needs to
process them.
Page 136
Matthew P Jones The Daily Design Pattern
Before we go, I want to point out a few things you should remember when dealing
with design patterns:
1. First and most importantly, it is ok to not use a pattern. These patterns solve
specific, definable problems, and if the problem you are trying to solve is more
complex or just not a good fit, you don’t have to make a pattern fit the
problem.
2. Secondly, the patterns described in this book are not the only ones available
to us developers. Patterns such as Repository, Unit of Work, Command/Query
Responsibility Segregation and Event Sourcing are extremely useful patterns
that were simply not found in the Gang of Four book. I wrote this book as a
way to introduce my dear readers to the more common patterns, from which
they can create their own or just use them as tools to solve problems.
A quick credit: the UML diagrams for the participants in this book are collected from
Do Factory’s examples. Check them out if you want more examples for these
patterns.
Page 137