0% found this document useful (0 votes)
118 views

Daily Design Pattern

This document describes the Factory Method design pattern over 23 days. It introduces the Factory Method pattern on day 1 as a creational pattern that defines an interface for creating objects but leaves the concrete implementations to subclasses. It provides an example using different types of sandwiches (bread, turkey, lettuce, mayonnaise) as the products and ingredients to demonstrate how the pattern works. The document will continue over the next 22 days to describe other common design patterns.

Uploaded by

Tiberiu Codreanu
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
118 views

Daily Design Pattern

This document describes the Factory Method design pattern over 23 days. It introduces the Factory Method pattern on day 1 as a creational pattern that defines an interface for creating objects but leaves the concrete implementations to subclasses. It provides an example using different types of sandwiches (bread, turkey, lettuce, mayonnaise) as the products and ingredients to demonstrate how the pattern works. The document will continue over the next 22 days to describe other common design patterns.

Uploaded by

Tiberiu Codreanu
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 138

Matthew P Jones The 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.

These patterns originated in a book


called Design Patterns: Elements of
Reusable Object-Oriented Software.
The four authors of this book (Erich
Gamma, Richard Helm, Ralph Johnson,
and John Vlissides) are commonly
referred to as the Gang of Four, and
thus the design patterns they named
are often collectively termed the Gang
of Four Design Patterns.

Software design patterns solve known,


specific problems in the field of
software development. They are called
“patterns” because the problems they
solve are common and pervasive;
every single person reading this book
will encounter these types of problems
at some point in their career. Thus,
design patterns are some of the most
useful tools in our developer toolbox.

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.

Come along with me as we explore the fundamental software design patterns,


implement them in C#, and grow our developer toolboxes. And, as always, thanks
for reading!

-Matthew P Jones, exceptionnotfound.net

Page 2
Matthew P Jones The Daily Design Pattern

DAY 1: THE FACTORY METHOD DESIGN PATTERN


Welcome to the official start of the Daily Design Pattern exercises! To kick us off,
we’re going to examine one of the simplest and most fundamental software design
pattern: Factory Method.

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.

According to Wikipedia, a sandwich...

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.”

Put two pieces of bread


around anything edible, and
it becomes a sandwich. Yes,
that means hot dogs are
sandwiches. That settles
that argument.

Let's build some C# classes


to demo how we can use
Factory Method to create a
variety of different
sandwiches.

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();

public List<Ingredient> Ingredients


{
get { return _ingredients; }
}
}

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());
}
}

Whenever wecreate an object of class


TurkeySandwich, we can call
CreateIngredients() to create the correct
amount and order of ingredients for this
sandwich.

But what if we wanted to go... bigger?

The sandwich in the photo to the left is often


called a Dagwood sandwich, named after a
comic strip character who was fond of making
them. In essence, a Dagwood is a ridiculously
large sandwich with a great many layers.

We want to create a class to represent a


Dagwood. What makes this patterns is that
with our Factory Method, all we need to do is
instantiate a class and override the
CreateIngredients() method, like in the
code on the next page.

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

Now, when we want to create objects of type TurkeySandwich or Dagwood, we simply


call them like this:

class Program
{
static void Main(string[] args)
{
var turkeySandwich = new TurkeySandwich();
var dagwood = new Dagwood();
//Do something with these sandwiches (like, say, eat them).
}
}

WILL I EVER USE THIS PATTERN?


Absolutely. The Factory Method pattern is exceedingly common in today's software
design world. Any time you need to create groups of related objects, utilizing the
Factory Method Design Pattern is one of the cleanest ways to do so.

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.

DAY 2: THE ABSTRACT FACTORY DESIGN PATTERN


The Abstract Factory Pattern is a Creational design pattern in which interfaces are
defined for creating families of related objects without specifying their actual
implementations.

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):

abstract class RecipeFactory


{
public abstract Sandwich CreateSandwich();
public abstract Dessert CreateDessert();
}

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

We also need a ConcreteFactory which implements the AbstractFactory and


returns the adult recipes:

// ConcreteFactory
class AdultCuisineFactory : RecipeFactory
{
public override Sandwich CreateSandwich()
{
return new BLT();
}

public override Dessert CreateDessert()


{
return new CremeBrulee();
}
}

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();
}

public override Dessert CreateDessert()


{
return new IceCreamSundae();
}
}

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();

var sandwich = factory.CreateSandwich();


var dessert = factory.CreateDessert();

Console.WriteLine("\nSandwich: " + sandwich.GetType().Name);


Console.WriteLine("Dessert: " + dessert.GetType().Name);

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!

WILL I EVER USE THIS PATTERN?


Unquestionably. Abstract Factory is an extremely common pattern, and as
mentioned earlier it enables architectures such as Dependency Injection.

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.

DAY 3: THE FAÇADE DESIGN PATTERN


For Day 3 of our Daily Design Pattern exercises, we’re going to model our first
Structural pattern: Façade.

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

PHOTO BY PETR SEVCOVIC / UNSPLASH


The server knows where to place each order and where to pick those parts of the
order up from. We'll model this relationship to demonstrate how the Facade pattern
can simplify the structure of our code.

First, let's create a class for the restaurant patron (example code on next page):

// Patron of the restaurant


class Patron
{
private string _name;

public Patron(string name)


{
this._name = name;
}

public string Name


{
get { return _name; }
}
}

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:

// All items sold in the restaurant must inherit from this.


class FoodItem { public int DishID; }

// Each section of the kitchen must implement this interface.


interface KitchenSection
{
FoodItem PrepDish(int DishID);
}

// Orders placed by Patrons.


class Order
{
public FoodItem Appetizer { get; set; }
public FoodItem Entree { get; set; }
public FoodItem Drink { get; set; }
}

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:

// The first division of the kitchen.


class ColdPrep : KitchenSection
{
public FoodItem PrepDish(int dishID)
{
//Go prep the cold item
return new FoodItem()
{
DishID = dishID
};
}
}

// The second division of the kitchen.


class HotPrep : KitchenSection
{
public FoodItem PrepDish(int dishID)
{
//Go prep the hot entree
return new FoodItem()
{
DishID = dishID
};
}
}

// The final division of the kitchen.


class Bar : KitchenSection
{
public FoodItem PrepDish(int dishID)
{
//Go mix the drink
return new FoodItem()
{
DishID = dishID
};
}
}

Page 17
Matthew P Jones The Daily Design Pattern

Finally, we need the actual Façade participant, which is our Server class:

// The actual "Facade" class


class Server
{
private ColdPrep _coldPrep = new ColdPrep();
private Bar _bar = new Bar();
private HotPrep _hotPrep = new HotPrep();

public Order PlaceOrder(Patron patron, int coldAppID, int


hotEntreeID, int drinkID)
{
Console.WriteLine("{0} places order for cold app #" +
coldAppID.ToString() + ", hot entree #" +
hotEntreeID.ToString() +
", and drink #" + drinkID.ToString() + ".");

Order order = new Order();

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):

static void Main(string[] args)


{
Server server = new Server();

Console.WriteLine("Hello! I'll be your server today. What is your


name?");
var name = Console.ReadLine();

Patron patron = new Patron(name);

Console.WriteLine("Hello " + patron.Name


+ ". What appetizer would you like? (1-15):");
var appID = int.Parse(Console.ReadLine());

Console.WriteLine("That’s a good one. What entree would you like?


(1-20):");
var entreeID = int.Parse(Console.ReadLine());

Console.WriteLine("A great choice! Finally, what drink would you


like? (1-60):");
var drinkID = int.Parse(Console.ReadLine());

Console.WriteLine("I'll get that order in right away.");

server.PlaceOrder(patron, appID, entreeID, drinkID);

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.

DAY 4: THE ADAPTER DESIGN PATTERN


We continue our daily design pattern exercises by examining another highly useful
Structural pattern: Adapter.

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.

This pattern is especially useful when attempting to adapt to an interface which


cannot be refactored (e.g. when the interface is controlled by a web service or API).

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 imagine that we


maintain a meat safe-cooking
temperature database. The
US Food & Drug
Administration maintains a
list of temperatures to which
meat must be cooked before
it is safe for human
consumption.

For this demo, we'll say that


we have an old, legacy
system which stores this
temperature data. Let’s first
discuss what such a system
might look like (this entire system is the Adaptee participant).

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:

public enum TemperatureType


{
Fahrenheit,
Celsius
}

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:

// The legacy API which must be converted to the new structure


class MeatDatabase
{
//...
public int GetCaloriesPerOunce(string meat)
{
switch (meat.ToLower())
{
case "beef": return 71;
case "pork": return 69;
case "chicken": return 66;
case "turkey": return 38; //Wow, turkey is lean!
default: return 0;
}
}

public double GetProteinPerOunce(string meat)


{
switch (meat.ToLower())
{
case "beef": return 7.33f;
case "pork": return 7.67f;
case "chicken": return 8.57f;
case "turkey": return 8.5f;
default: return 0d;
}
}
}

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.

In our new system, we are trying to keep to object-oriented principles. Therefore, we


will need a Meat object that keeps track of its own various properties. Let’s create
that object, which will be our Target participant:

Page 23
Matthew P Jones The Daily Design Pattern

// The new Meat class, which represents details about a particular


kind of meat.
class Meat
{
protected string MeatName;
protected float SafeCookTempFahrenheit;
protected float SafeCookTempCelsius;
protected double CaloriesPerOunce;
protected double ProteinPerOunce;

// Constructor
public Meat(string meat)
{
this.MeatName = meat;
}

public virtual void LoadData()


{
Console.WriteLine("\nMeat: {0} ------ ", MeatName);
}
}

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:

// The Adapter class


class MeatDetails : Meat
{
private MeatDatabase _meatDatabase;

// Constructor
public MeatDetails(string name) : base(name) { }

public override void LoadData()


{
// The Adaptee
_meatDatabase = new MeatDatabase();

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:

static void Main(string[] args)


{
//Non-adapted
Meat unknown = new Meat("Beef");
unknown.LoadData();

//Adapted
MeatDetails beef = new MeatDetails("Beef");
beef.LoadData();

MeatDetails turkey = new MeatDetails("Turkey");


turkey.LoadData();

MeatDetails chicken = new MeatDetails("Chicken");


chicken.LoadData();

Console.ReadKey();
}

We can see some example output from


running this application in the screenshot on
the right.

Just like that, we've overcome the fact that


we cannot refactor the legacy API, and now
we can properly model these classes in an
object-oriented style. In other words, we
have successfully implemented the Adapter
Design Pattern!

WILL I EVER USE THIS PATTERN?


Most likely. As I've been mentioning, the
pattern is extremely useful when you're
trying to adapt old or legacy systems to new
designs, so if you're ever in that situation
the Adapter pattern might be the best fit for
your project.

Note that the Adapter pattern and the


Façade pattern from Day 3 appear very similar at first glance. They are, however,
used in different ways:

Page 26
Matthew P Jones The Daily Design Pattern

• Façade creates a new interface; Adapter re-uses an existing one.


• Façade hides several interfaces; Adapter makes two existing ones work
together.
• Façade is the equivalent of saying "These two classes are never going to work
together; I will build my own."; Adapter is the equivalent of "Of course it will
work, it just needs a little tweaking."

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.

Now, if you’ll excuse me, I think I need to go grill something.

DAY 5: THE BRIDGE DESIGN PATTERN


The Bridge design pattern seeks to decouple an abstraction from its implementation
such that both can vary independently. Effectively, the Bridge maintains a reference
to both abstraction and implemention but doesn't implement either, thereby allowing
the details of both to remain in their separate classes.

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).

In his honor, let's model a


system by which we can
order various special-
needs meals from many
different restaurants.

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.

THE TRADITIONAL WAY


In a traditional inheritance model, we might have the following classes:

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

USING THE BRIDGE PATTERN


The Bridge design pattern seeks to divide the responsibility of these interfaces such
that they're much more reusable. What we want is to end up with something like
this:

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:

// Implementor which defines an interface for placing an order


public interface IOrderingSystem
{
void Place(string 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:

// Abstraction which represents the sent order and maintains a


reference to the restaurant where the order is going.
public abstract class SendOrder
{
//Reference to the Implementor
public IOrderingSystem _restaurant;

public abstract void Send();


}

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).

public class DinerOrders : IOrderingSystem


{
public void Place(string order)
{
Console.WriteLine("Placing order for " + order
+ " at the Diner.");
}
}

public class FancyRestaurantOrders : IOrderingSystem


{
public void Place(string order)
{
Console.WriteLine("Placing order for " + order
+ " at the Fancy Restaurant.");
}
}

Finally, we create a Main() method which uses the Bridge to create different orders
and send them to different restaurants.

static void Main(string[] args)


{
SendOrder _sendOrder = new SendDairyFreeOrder();
_sendOrder._restaurant = new DinerOrders();
_sendOrder.Send();

_sendOrder._restaurant = new FancyRestaurantOrders();


_sendOrder.Send();

_sendOrder = new SendGlutenFreeOrder();


_sendOrder._restaurant = new DinerOrders();
_sendOrder.Send();

_sendOrder._restaurant = new FancyRestaurantOrders();


_sendOrder.Send();

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.

Here's a screenshot of the demo app in action:

WILL I EVER USE THIS PATTERN?


Probably. As mentioned above, this pattern is very useful when designing systems
where multiple different kinds of inheritance are possible; Bridge allows you to
implement these inheritances without tightly binding to their abstractions.

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…

DAY 6: THE TEMPLATE METHOD DESIGN PATTERN


Today we will create our first Behavioral design pattern: Template Method.

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

PHOTO BY KATE REMNER / UNSPLASH


While acknowledging that this doesn't necessarily cover all kinds of bread that are
possible to make, let's say for the sake of simplicity that there are three basic steps
in making bread:

1. Mix the ingredients together.


2. Bake the mixture.
3. Slice the resulting bread.

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:

// The AbstractClass participant which contains the template method.


abstract class Bread
{
public abstract void MixIngredients();

public abstract void Bake();

public virtual void Slice()


{
Console.WriteLine("Slicing the "
+ GetType().Name + " bread!");
}

// The template method


public void Make()
{
MixIngredients();
Bake();
Slice();
}
}

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

Let's extend this example by implementing several ConcreteClass objects for


different types of bread:

class TwelveGrain : Bread


{
public override void MixIngredients()
{
Console.WriteLine("Gathering Ingredients for 12-Grain.");
}

public override void Bake()


{
Console.WriteLine("Baking the 12-Grain. (25 minutes)");
}
}

class Sourdough : Bread


{
public override void MixIngredients()
{
Console.WriteLine("Gathering Ingredients for Sourdough.");
}

public override void Bake()


{
Console.WriteLine("Baking the Sourdough. (20 minutes)");
}
}

class WholeWheat : Bread


{
public override void MixIngredients()
{
Console.WriteLine("Gathering Ingredients for Whole Wheat.");
}

public override void Bake()


{
Console.WriteLine("Baking the Whole Wheat. (15 minutes)");
}
}

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

static void Main(string[] args)


{
Sourdough sourdough = new Sourdough();
sourdough.Make();

TwelveGrain twelveGrain = new TwelveGrain();


twelveGrain.Make();

WholeWheat wholeWheat = new WholeWheat();


wholeWheat.Make();

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.

WILL I EVER USE THIS PATTERN?


Almost certainly. I'd be willing to bet that most of you dear readers have already
used this pattern and may not have known what it was called. This pattern is
extremely common, flexible, and useful for many different applications and scenarios.

...But. It's not without problems. Jimmy Bogard explains:

"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

DAY 7: THE ITERATOR DESIGN PATTERN


The Iterator design pattern provides a way to access objects in an underlying
representation without exposing access to the representation itself.

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

PHOTO BY PATRICK FORE / UNSPLASH


For this simple pattern, we’re going to build a collection for a group of jelly beans and
have that collection create an iterator for itself. But before we can do that, we must
define a class that represents a single bean.

class JellyBean
{
private string _flavor;

// Constructor
public JellyBean(string flavor)
{
this._flavor = flavor;
}

public string Flavor


{
get { return _flavor; }
}
}

Next, we need both our Aggregate and ConcreteAggregate participants, which


represent a collection of jelly beans.

Page 40
Matthew P Jones The Daily Design Pattern

/// The aggregate interface


interface ICandyCollection
{
IJellyBeanIterator CreateIterator();
}

/// The ConcreteAggregate class


class JellyBeanCollection : ICandyCollection
{
private ArrayList _items = new ArrayList();

public JellyBeanIterator CreateIterator()


{
return new JellyBeanIterator(this);
}

public int Count


{
get { return _items.Count; }
}

// Indexer
public object this[int index]
{
get { return _items[index]; }
set { _items.Add(value); }
}
}

Now, we can define our Iterator and ConcreteIterator participants (example


code on the next page).

Page 41
Matthew P Jones The Daily Design Pattern

// The 'Iterator' interface


interface IJellyBeanIterator
{
JellyBean First();
JellyBean Next();
bool IsDone { get; }
JellyBean CurrentBean { get; }
}

// The 'ConcreteIterator' class


class JellyBeanIterator : IJellyBeanIterator
{
private JellyBeanCollection _jellyBeans;
private int _current = 0;
private int _step = 1;

public JellyBeanIterator(JellyBeanCollection beans)


{
this._jellyBeans = beans;
}

public JellyBean First()


{
_current = 0;
return _jellyBeans[_current] as JellyBean;
}

public JellyBean Next()


{
_current += _step;
if (!IsDone) return _jellyBeans[_current] as JellyBean;
else return null;
}

public JellyBean CurrentBean


{
get { return _jellyBeans[_current] as JellyBean; }
}

public bool IsDone


{
get { return _current >= _jellyBeans.Count; }
}
}

Page 42
Matthew P Jones The Daily Design Pattern

Notice that the ConcreteAggregate needs to implement methods by which we can


manipulate objects within the collection, without exposing the collection itself. This is
how it can fit with the Iterator design pattern.

Finally, in our Main(), we can create a collection of jelly beans and then iterate over
them:

static void Main(string[] args)


{
// Build a collection of jelly beans
JellyBeanCollection collection = new JellyBeanCollection();
collection[0] = new JellyBean("Cherry");
collection[1] = new JellyBean("Bubble Gum");
collection[2] = new JellyBean("Root Beer");
collection[3] = new JellyBean("French Vanilla");
collection[4] = new JellyBean("Licorice");
collection[5] = new JellyBean("Buttered Popcorn");
collection[6] = new JellyBean("Juicy Pear");
collection[7] = new JellyBean("Cinnamon");
collection[8] = new JellyBean("Coconut");

// Create iterator
JellyBeanIterator iterator = collection.CreateIterator();

Console.WriteLine("Gimme all the jelly beans!");

for (JellyBean item = iterator.First();


!iterator.IsDone; item = iterator.Next())
{
Console.WriteLine(item.Flavor);
}

Console.ReadKey();
}

Now our Iterator class is able to iterate over the entire collection of jelly beans and
output their flavors!

WILL I EVER USE THIS PATTERN?


Absolutely. The pattern is astonishingly useful when attempting to retrieve objects
from collections that you'd rather not expose to outside usage (because that's the
pattern's entire purpose). If you primarily work in the ASP.NET world (as I do) and

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.

DAY 8: THE OBSERVER DESIGN PATTERN


The Observer pattern seeks to allow objects to notify their observers when their
internal state changes.

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

• The ConcreteSubject objects


store the states of interest to the
Observers and are responsible
for sending a notification when
the ConcreteSubject's state
changes.
• The Observer defines an
updating interface for objects
that should be notified of
changes in a Subject.

• The ConcreteObserver objects maintain a reference to a ConcreteSubject


and implement the Observer updating interface to keep its state consistent
with that of the Subject's.

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).

On some days, the


vegetables will be more
expensive than on other
days, due to factors like
the size of the harvest or
the size of the
vegetables themselves.
Our system will need to
notify “observer”
objects that prices have
changed, when they do
so. Further, we need to
allow restaurants to
watch the prices and
place an order when the
price for a particular
vegetable falls below a
specified threshold, which is different for each restaurant.

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

// Subject abstract class


abstract class Veggies
{
private double _pricePerPound;
private List<IRestaurant> _restaurants = new List<IRestaurant>();

public Veggies(double pricePerPound)


{
_pricePerPound = pricePerPound;
}

public void Attach(IRestaurant restaurant)


{
_restaurants.Add(restaurant);
}

public void Detach(IRestaurant restaurant)


{
_restaurants.Remove(restaurant);
}

public void Notify()


{
foreach (IRestaurant restaurant in _restaurants)
{
restaurant.Update(this);
}

Console.WriteLine("");
}

public double PricePerPound


{
get { return _pricePerPound; }
set
{
if (_pricePerPound != value)
{
_pricePerPound = value;
Notify(); //Notify our observers of price changes
}
}
}
}

Page 46
Matthew P Jones The Daily Design Pattern

We also need a ConcreteSubject which represents the price of a specific vegetable;


in this case, carrots.

// 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:

// The Observer interface


interface IRestaurant
{
void Update(Veggies veggies);
}

Page 47
Matthew P Jones The Daily Design Pattern

Finally we need our ConcreteObserver class, which represent specific restaurants.


This class must implement the Update() method from IRestaurant. (The example
code for this is on the next page).

Note that the Restaurants will want to buy veggies if the price dips below a certain
threshold amount, which differs per restaurant.

// The ConcreteObserver class


class Restaurant : IRestaurant
{
private string _name;
private Veggies _veggie;
private double _purchaseThreshold;

public Restaurant(string name, double purchaseThreshold)


{
_name = name;
_purchaseThreshold = purchaseThreshold;
}

public void Update(Veggies veggie)


{
Console.WriteLine("Notified {0} of {1}'s "
+ " price change to {2:C} per pound.",
_name, veggie.GetType().Name,
veggie.PricePerPound);

if(veggie.PricePerPound < _purchaseThreshold)


{
Console.WriteLine(_name + " wants to buy some "
+ veggie.GetType().Name + "!");
}
}
}

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:

static void Main(string[] args)


{
// Create price watch for Carrots and attach restaurants that buy
carrots from suppliers.
Carrots carrots = new Carrots(0.82);
carrots.Attach(new Restaurant("Mackay's", 0.77));
carrots.Attach(new Restaurant("Johnny's Sports Bar", 0.74));
carrots.Attach(new Restaurant("Salad Kingdom", 0.75));

// Fluctuating carrot prices will notify subscribing restaurants.


carrots.PricePerPound = 0.79;
carrots.PricePerPound = 0.76;
carrots.PricePerPound = 0.74;
carrots.PricePerPound = 0.81;

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!)

WILL I EVER USE


THIS PATTERN?
Most likely. This is a
fairly common pattern,
and the ability to automatically notify dependent objects of a subject's state change
is highly desirable in my opinion. However, as with all software design patterns, be

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.

DAY 9: THE MEMENTO DESIGN PATTERN


The Memento pattern seeks to capture and externalize and object's state so that the
object can be restored to this state at a later time.

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.

var memento = someBlogger.CreateMemento(); //Hungry


someBlogger.startWriting(); //Change state to writing

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.

In our system, we need to


keep track of how much
information we enter
about a particular
supplier, and be able to
restore that information
to a previous state if we,
say, accidentally enter the
wrong address. We can
PHOTO BY ANNA PELZER / UNSPLASH demo this using the
Memento pattern.

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;

public string Name


{
get { return _name; }
set
{
_name = value;
Console.WriteLine("Proprietor: " + _name);
}
}

public string Phone


{
get { return _phone; }
set
{
_phone = value;
Console.WriteLine("Phone Number: " + _phone);
}
}

public string Address


{
get { return _address; }
set
{
_address = value;
Console.WriteLine("Address: " + _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
{
// ...

public FoodSupplierMemento SaveMemento()


{
Console.WriteLine("\nSaving current state\n");
return new FoodSupplierMemento(_name, _phone, _address);
}

public void RestoreMemento(FoodSupplierMemento memento)


{
Console.WriteLine("\nRestoring previous state\n");
Name = memento.Name;
Phone = memento.PhoneNumber;
Address = memento.Address;
}
}

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.

// The Memento class


class FoodSupplierMemento
{
public string Name { get; set; }
public string PhoneNumber { get; set; }
public string Address { get; set; }

public FoodSupplierMemento(string name, string phone,


string address)
{
Name = name;
PhoneNumber = phone;
Address = address;
}
}

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;

public FoodSupplierMemento Memento


{
set { _memento = value; }
get { return _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:

static void Main(string[] args)


{
//Here's a new supplier for our restaurant
FoodSupplier s = new FoodSupplier();
s.Name = "Giada DeLaurentiis";
s.Phone = "(482) 555-1172";

// Let's store that entry in our database.


SupplierMemory m = new SupplierMemory();
m.Memento = s.SaveMemento();

// Continue changing originator


s.Address = "548 S Main St. Nowhere, KS";

// Oops, need to undo that entry, I entered the wrong address


s.RestoreMemento(m.Memento);

Console.ReadKey();
}

WILL I EVER USE THIS PATTERN?


If you’re ever needing to implement an undo/redo system, you will most likely need
to use the Memento design pattern. Other than that, though, I have struggled to

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.

Oh, I almost forgot something.

someBlogger.FinishWriting();
someBlogger.RestoreState(memento); //Hungry again!

DAY 10: THE PROTOTYPE DESIGN PATTERN


The Prototype Design Pattern is a Creational pattern in which objects are created
using a prototypical instance of said object. This pattern is particularly useful for
creating lots of instances of an object, all of which share some or all of their values.

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

• The ConcretePrototype implements the cloning operation defined in the


Prototype.
• The Client creates a new
object by asking the
Prototype to clone itself.

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.

(As you can probably tell, I like sandwiches. A lot.)

In the picture to the


left, there are many
kinds of sandwiches.
Just like the color
example above, a
sandwich is still a
sandwich no matter
what's between the
two slices of bread.

Let's demo how we


can use the
Prototype pattern to
build lots of
sandwiches.

First, we'll create an


abstract class (the Prototype participant) to represent a sandwich, and define a
method by which the abstract Sandwich class can clone itself:

/// The Prototype abstract class


abstract class SandwichPrototype
{
public abstract SandwichPrototype Clone();
}

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

class Sandwich : SandwichPrototype


{
private string Bread;
private string Meat;
private string Cheese;
private string Veggies;

public Sandwich(string bread, string meat,


string cheese, string veggies)
{
Bread = bread;
Meat = meat;
Cheese = cheese;
Veggies = veggies;
}

public override SandwichPrototype Clone()


{
string ingredientList = GetIngredientList();
Console.WriteLine("Cloning sandwich with ingredients: {0}",
ingredientList.Remove(ingredientList.LastIndexOf(",")));

return MemberwiseClone() as SandwichPrototype;


}

private string GetIngredientList() {...}


}

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>();

public SandwichPrototype this[string name]


{
get { return _sandwiches[name]; }
set { _sandwiches.Add(name, value); }
}
}

With our infrastructure created, it is now time to create a BUNCH of sandwiches.

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();

// Initialize with default sandwiches


sandwichMenu["BLT"] =
new Sandwich("Wheat", "Bacon", "", "Lettuce, Tomato");
sandwichMenu["PB&J"] =
new Sandwich("White", "", "", "Peanut Butter, Jelly");
sandwichMenu["Turkey"] =
new Sandwich("Rye", "Turkey", "Swiss", "Lettuce, Onion,
Tomato");

// Deli manager adds custom sandwiches


sandwichMenu["LoadedBLT"] =
new Sandwich("Wheat", "Turkey, Bacon", "American",
"Lettuce, Tomato, Onion, Olives");
sandwichMenu["ThreeMeatCombo"] =
new Sandwich("Rye", "Turkey, Ham, Salami",
"Provolone", "Lettuce, Onion");
sandwichMenu["Vegetarian"]
= new Sandwich("Wheat", "", "",
"Lettuce, Onion, Tomato, Olives, Spinach");

// Now we can clone these sandwiches


Sandwich sandwich1 = sandwichMenu["BLT"].Clone() as Sandwich;
Sandwich sandwich2 =
sandwichMenu["ThreeMeatCombo"].Clone() as Sandwich;
Sandwich sandwich3 =
sandwichMenu["Vegetarian"].Clone() as Sandwich;

// Wait for user


Console.ReadKey();
}
}

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

WILL I EVER USE THIS PATTERN?


Possibly. It's a good idea if you have the scenario described above. However, I'm
not sure how common that scenario is in regular day-to-day coding; I haven't
(consciously) implemented this pattern in several years.

The situation in which I see this pattern as being the most useful is when all of the
following happens:

1. You need to create a lot of instances of an object,


2. AND those instances will be the same or similar as the prototypical instance.
3. AND creating a new instance of this object would be markedly slower than
cloning an existing instance.

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.

DAY 11: THE SINGLETON DESIGN PATTERN


The Singleton design pattern is a Creational pattern in which a class is guaranteed to
only ever have exactly one instance, with that instance being globally accessible.

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

• The Singleton is a class which defines


exactly one instance of itself, and that
instance is globally accessible.

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.

In movies, one of the best ways


to identify that the characters
are in a diner or other quick-
service restaurant is by having
an overweight chef with a dirty
apron hit a bell and yell out
"Order Up!". The thing about that
bell is that there's probably only
ever one; the sound is used to
notify the servers that the next
order is at the window and needs
to be taken to the tables.

If there's only ever one, we can


model that as a Singleton.

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;
}
}

public void Ring()


{
Console.WriteLine("Ding! Order up!");
}
}

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.

THIS PATTERN HAS PROBLEMS


Singleton is probably the most maligned Design Pattern, and for good reason.

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.

WILL I EVER USE THIS PATTERN?


Not on purpose.

(Kidding, kidding. Sort of.)

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.

DAY 12: THE FLYWEIGHT DESIGN PATTERN


The Flyweight design pattern is used to create lots of small, related objects without
invoking a lot of overhead work in doing so, thereby improving performance and
maintainability.

The idea is that each Flyweight object has two pieces:

• 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.

First, let's build a Slider abstract class (the Flyweight participant):

/// The Flyweight class


abstract class Slider
{
protected string Name;
protected string Cheese;
protected string Toppings;
protected decimal Price;

public abstract void Display(int orderTotal);


}

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;
}

public override void Display(int orderTotal)


{
Console.WriteLine("Slider #" + orderTotal + ": " + Name
+ " - topped with " + Cheese
+ " cheese and " + Toppings
+ "! $" + Price.ToString());
}
}

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;
}

public override void Display(int orderTotal)


{
Console.WriteLine("Slider #" + orderTotal + ": " + Name
+ " - topped with " + Cheese
+ " cheese and " + Toppings
+ "! $" + Price.ToString());
}
}

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;
}

public override void Display(int orderTotal)


{
Console.WriteLine("Slider #" + orderTotal + ": " + Name
+ " - topped with " + Cheese
+ " cheese and " + Toppings
+ "! $" + Price.ToString());
}
}

Page 68
Matthew P Jones The Daily Design Pattern

Finally, we need our FlyweightFactory participant, which will create Flyweight


objects. The Factory will store a collection of already-created sliders, and any time
another slider of the same type needs to be created, the Factory will use the already-
created one rather than creating a brand-new one. The code for this is on the next
page.

// The FlyweightFactory class


class SliderFactory
{
private Dictionary<char, Slider> _sliders =
new Dictionary<char, Slider>();

public Slider GetSlider(char key)


{
Slider slider = null;
if (_sliders.ContainsKey(key))
{ slider = _sliders[key]; }
else //Otherwise, create a brand new instance of the slider.
{
switch (key)
{
case 'B': slider = new BaconMaster(); break;
case 'V': slider = new VeggieSlider(); break;
case 'Q': slider = new BBQKing(); break;
}
_sliders.Add(key, slider);
}
return slider;
}
}

Page 69
Matthew P Jones The Daily Design Pattern

All of this comes together in our Main() method (which is also


our Client participant). Let's pretend we are an order system and we need to take
orders for these sliders; the patron can order as many kinds of sliders as s/he wants.

static void Main(string[] args)


{
Console.WriteLine("Please enter your slider order (B, V, Z):");
var order = Console.ReadLine();
char[] chars = order.ToCharArray();
SliderFactory factory = new SliderFactory();
int orderTotal = 0;

//Get the slider from the factory


foreach (char c in chars)
{
orderTotal++;
Slider character = factory.GetSlider(c);
character.Display(orderTotal);
}
Console.ReadKey();
}

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

WILL I EVER USE THIS PATTERN?


To be honest, probably not. In theory, this pattern could improve performance, but
in practice it's limited to scenarios where you find yourself creating a lot of objects
from one or more templates. Further, the entire point of this pattern is to improve
performance, and performance is generally not an issue until you can prove that it
is, so while refactoring to this pattern may be useful in some extreme circumstances,
for most people and most projects the overhead and complexity of the Flyweight
pattern outweigh the benefits.

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!

DAY 13: THE BUILDER DESIGN PATTERN


The Builder pattern separates the construction of an object from its representation
so that the same construction process can create different representations.

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

• The ConcreteBuilder constructs and assembles parts of the product by


implementing
the Builder interface. It
must also define and
track the representation
it creates.
• The Product represents
the object being
constructed. It includes
classes for defining the
parts of the object,
including any interfaces for assembling the parts into the final result.
• The Director constructs an object using the Builder interface.

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.

Here's the thing about sandwiches: as


we discussed during Day 1
demonstrating the Factory Method
pattern, the only thing that defines a
sandwich is something edible between
two slices of bread. That's it.

That said, different types of


sandwiches require different steps in
order to make them, but they're still
just sandwiches. Most of the time, the
same kinds of ingredients will be used
to create many different kinds of
sandwiches. Let's see how we can use
the Builder pattern to build us some of
these yummy sandwiches.

PHOTO BY MAE MU / UNSPLASH We’re going to start building the


example for this design pattern a bit
differently, in that we’re building the “highest level” participant first. We need to
implement the Director participant. We'll call our Director AssemblyLine, make it a
class, and it will define in what steps the process of making a sandwich are called.

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>();

public Sandwich(string sandwichType)


{
this._sandwichType = sandwichType;
}

public string this[string key]


{
get { return _ingredients[key]; }
set { _ingredients[key] = value; }
}

public void Show()


{
Console.WriteLine("\n---------------------------");
Console.WriteLine("Sandwich: {0}", _sandwichType);
Console.WriteLine(" Bread: {0}", _ingredients["bread"]);
Console.WriteLine(" Meat: {0}", _ingredients["meat"]);
Console.WriteLine(" Cheese: {0}", _ingredients["cheese"]);
Console.WriteLine(" Veggies: {0}", _ingredients["veggies"]);
Console.WriteLine(" Condiments: {0}", _ingredients["condiments"]);
}
}

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:

// The Builder abstract class


abstract class SandwichBuilder
{
protected Sandwich sandwich;

// Gets sandwich instance


public Sandwich Sandwich
{
get { return sandwich; }
}

// Abstract build methods


public abstract void AddBread();
public abstract void AddMeats();
public abstract void AddCheese();
public abstract void AddVeggies();
public abstract void AddCondiments();
}

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

Next, let's implement a few ConcreteBuilder classes to build some specific


sandwiches. We’ll start with that classic, all-time great sandwich: a turkey club.

// A ConcreteBuilder class
class TurkeyClub : SandwichBuilder
{
public TurkeyClub()
{
sandwich = new Sandwich("Turkey Club");
}

public override void AddBread()


{
sandwich["bread"] = "12-Grain";
}

public override void AddMeats()


{
sandwich["meat"] = "Turkey";
}

public override void AddCheese()


{
sandwich["cheese"] = "Swiss";
}

public override void AddVeggies()


{
sandwich["veggies"] = "Lettuce, Tomato";
}

public override void AddCondiments()


{
sandwich["condiments"] = "Mayo";
}
}

Page 75
Matthew P Jones The Daily Design Pattern

Let’s also add another all-time great sandwich, a BLT:

// A ConcreteBuilder class
class BLT : SandwichBuilder
{
public BLT()
{
sandwich = new Sandwich("BLT");
}

public override void AddBread()


{
sandwich["bread"] = "Wheat";
}

public override void AddMeats()


{
sandwich["meat"] = "Bacon";
}

public override void AddCheese()


{
sandwich["cheese"] = "None";
}

public override void AddVeggies()


{
sandwich["veggies"] = "Lettuce, Tomato";
}

public override void AddCondiments()


{
sandwich["condiments"] = "Mayo, Mustard";
}
}

Page 76
Matthew P Jones The Daily Design Pattern

Finally, let’s add my personal favorite, a ham and cheese:

// A ConcreteBuilder class
class HamAndCheese : SandwichBuilder
{
public HamAndCheese()
{
sandwich = new Sandwich("Ham and Cheese");
}

public override void AddBread()


{
sandwich["bread"] = "White";
}

public override void AddMeats()


{
sandwich["meat"] = "Ham";
}

public override void AddCheese()


{
sandwich["cheese"] = "American";
}

public override void AddVeggies()


{
sandwich["veggies"] = "None";
}

public override void AddCondiments()


{
sandwich["condiments"] = "Mayo";
}
}

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:

static void Main(string[] args)


{
SandwichBuilder builder;

// Create shop with sandwich assembly line


AssemblyLine shop = new AssemblyLine();

// Construct and display sandwiches


builder = new HamAndCheese();
shop.Assemble(builder);
builder.Sandwich.Show();

builder = new BLT();


shop.Assemble(builder);
builder.Sandwich.Show();

builder = new TurkeyClub();


shop.Assemble(builder);
builder.Sandwich.Show();

// Wait for user


Console.ReadKey();
}

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.

(Yes, that pun was intentional. No, I'm not sorry.)

WILL I EVER USE THIS PATTERN?


Probably not. Let's face it, this is a lot of work to build these supposedly related
items in a reusable manner. The patterns some degree of assumptions about how
these objects should be created, and for me it's too many assumptions to rely on
using this pattern in common projects. Seems to me like the Builder pattern has
some uses, just not a lot of them.

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!

DAY 14: THE STATE DESIGN PATTERN


On this day, we will deal with one of the most useful and most widespread design
patterns in the modern world: State.

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).

// The State abstract class


abstract class Doneness
{
protected Steak steak;
protected double currentTemp;
protected double lowerTemp;
protected double upperTemp;
protected bool canEat;

public Steak Steak


{
get { return steak; }
set { steak = value; }
}

public double CurrentTemp


{
get { return currentTemp; }
set { currentTemp = value; }
}

public abstract void AddTemp(double temp);


public abstract void RemoveTemp(double temp);
public abstract void DonenessCheck();
}

The abstract methods AddTemp(), RemoveTemp(), and DonenessCheck() will need to


be implemented by each of the states we can place the steak in.

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).

We also need to implement the method DonenessCheck(), which determines whether


or not the internal temperature of the steak is sufficiently high enough to allow it to
move to another state. In this case, we'll make the assumption that a steak may only
move to the next state of Rare.

Page 81
Matthew P Jones The Daily Design Pattern

/// A Concrete State class.


class Uncooked : Doneness
{
public Uncooked(Doneness state)
{
currentTemp = state.CurrentTemp;
steak = state.Steak;
Initialize();
}

private void Initialize()


{
lowerTemp = 0;
upperTemp = 130;
canEat = false;
}

public override void AddTemp(double amount)


{
currentTemp += amount;
DonenessCheck();
}

public override void RemoveTemp(double amount)


{
currentTemp -= amount;
DonenessCheck();
}

public override void DonenessCheck()


{
if (currentTemp > upperTemp)
steak.State = new Rare(this);
}
}

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) { }

public Rare(double currentTemp, Steak steak)


{
this.currentTemp = currentTemp;
this.steak = steak;
canEat = true; //We can now eat the steak
Initialize();
}

private void Initialize()


{
lowerTemp = 130;
upperTemp = 139.999999999999;
canEat = true;
}

public override void AddTemp(double amount)


{
currentTemp += amount;
DonenessCheck();
}

public override void RemoveTemp(double amount)


{
currentTemp -= amount;
DonenessCheck();
}

public override void DonenessCheck()


{
if (currentTemp < lowerTemp)
steak.State = new Uncooked(this);
else if (currentTemp > upperTemp)
steak.State = new MediumRare(this);
}
}

Page 83
Matthew P Jones The Daily Design Pattern

In a similar manner, we implement states for MediumRare, Medium, and WellDone.


(For the sake of simplicity I am skipping the Medium Well state).

class MediumRare : Doneness


{
public MediumRare(Doneness state)
: this(state.CurrentTemp, state.Steak) { }

public MediumRare(double currentTemp, Steak steak)


{
this.currentTemp = currentTemp;
this.steak = steak;
canEat = true;
Initialize();
}

private void Initialize()


{
lowerTemp = 140;
upperTemp = 154.9999999999;
}

public override void AddTemp(double amount)


{
currentTemp += amount;
DonenessCheck();
}

public override void RemoveTemp(double amount)


{
currentTemp -= amount;
DonenessCheck();
}

public override void DonenessCheck()


{
if (currentTemp < 0.0)
steak.State = new Uncooked(this);
else if (currentTemp < lowerTemp)
steak.State = new Rare(this);
else if (currentTemp > upperTemp)
steak.State = new Medium(this);
}
}

Page 84
Matthew P Jones The Daily Design Pattern

class Medium : Doneness


{
public Medium(Doneness state)
: this(state.CurrentTemp, state.Steak) { }

public Medium(double currentTemp, Steak steak)


{
this.currentTemp = currentTemp;
this.steak = steak;
canEat = true;
Initialize();
}

private void Initialize()


{
lowerTemp = 155;
upperTemp = 169.9999999999;
}

public override void AddTemp(double amount)


{
currentTemp += amount;
DonenessCheck();
}

public override void RemoveTemp(double amount)


{
currentTemp -= amount;
DonenessCheck();
}

public override void DonenessCheck()


{
if (currentTemp < 130)
steak.State = new Uncooked(this);
else if (currentTemp < lowerTemp)
steak.State = new MediumRare(this);
else if (currentTemp > upperTemp)
steak.State = new WellDone(this);
}
}

Page 85
Matthew P Jones The Daily Design Pattern

class WellDone : Doneness //aka Ruined


{
public WellDone(Doneness state)
: this(state.CurrentTemp, state.Steak) { }

public WellDone(double currentTemp, Steak steak)


{
this.currentTemp = currentTemp;
this.steak = steak;
canEat = true;
Initialize();
}

private void Initialize()


{
lowerTemp = 170;
upperTemp = 230;
}

public override void AddTemp(double amount)


{
currentTemp += amount;
DonenessCheck();
}

public override void RemoveTemp(double amount)


{
currentTemp -= amount;
DonenessCheck();
}

public override void DonenessCheck()


{
if (currentTemp < 0)
steak.State = new Uncooked(this);
else if (currentTemp < lowerTemp)
steak.State = new Medium(this);
}
}

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

// The Context class


class Steak
{
private Doneness _state;
private string _beefCut;

public Steak(string beefCut)


{
_cook = beefCut;
_state = new Rare(0.0, this);
}

public double CurrentTemp


{
get { return _state.CurrentTemp; }
}

public Doneness State


{
get { return _state; }
set { _state = value; }
}

public void AddTemp(double amount)


{
_state.AddTemp(amount);
Console.WriteLine("Increased temp by {0} degrees.", amount);
Console.WriteLine(" Current temp is {0}", CurrentTemp);
Console.WriteLine(" Status is {0}", State.GetType().Name);
Console.WriteLine("");
}

public void RemoveTemp(double amount)


{
_state.RemoveTemp(amount);
Console.WriteLine("Decreased temp by {0} degrees.", amount);
Console.WriteLine(" Current temp is {0}", CurrentTemp);
Console.WriteLine(" Status is {0}", State.GetType().Name);
Console.WriteLine("");
}
}

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:

static void Main(string[] args)


{
//Let's cook a steak!
Steak account = new Steak("T-Bone");

// Apply temperature changes


account.AddTemp(120);
account.AddTemp(15);
account.AddTemp(15);
account.RemoveTemp(10); //Yes I know cooking doesn't work this way
account.RemoveTemp(15);
account.AddTemp(20);
account.AddTemp(20);
account.AddTemp(20);

Console.ReadKey();
}

Page 88
Matthew P Jones The Daily Design Pattern

As we change the temperature, we


change the state of the Steak object.
The output of this method looks
something like the screenshot on the
right.

As the Steak class's internal


temperature changes,
the Doneness state in which it
currently resides also changes, and
consequently the apparent behavior of
that object shifts to whatever behavior
is defined by the current state.

WILL I EVER USE THIS PATTERN?


Most likely, especially if you deal with
objects which change behaviors as
their internal state changes. I
personally have a lot of experience
with this pattern, as I built a Workflow
Engine database which is this pattern
writ large and made changeable.

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

DAY 15: THE STRATEGY DESIGN PATTERN


Today we will demonstrate a pattern that is closely related to the State design pattern
we discussed yesterday: the Strategy 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.

When cooking various kinds of food,


particularly meats, there's often more
than one way to cook them to safe eating
temperatures. For example, you might
grill them, bake them, deep-fry them, or
broil them, depending on whether you
have friends over, how much you want to
show off your cooking skills, and how
many burns you are willing to suffer. Each
of these methods will get the item cooked,
just via different processes. These
processes, in object-oriented code, can
each be their own class.

In our example, let's pretend that we'll


ask the user what method they'd like to
use to cook their food, and then
implement that method using the
Strategy design pattern.

First, let's write up the Strategy


participant, which for our demo is an
PHOTO BY PAUL HERMANN / UNSPLASH abstract class.

/// 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

// A Concrete Strategy class


class Grilling : CookStrategy
{
public override void Cook(string food)
{
Console.WriteLine("\nCooking " + food + " by grilling it.");
}
}

// A Concrete Strategy class


class OvenBaking : CookStrategy
{
public override void Cook(string food)
{
Console.WriteLine("\nCooking " + food + " by oven baking it.");
}
}

// A Concrete Strategy class


class DeepFrying : CookStrategy
{
public override void Cook(string food)
{
Console.WriteLine("\nCooking " + food + " by deep frying it");
}
}

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:

// The Context class, which keeps a reference to the chosen Strategy.


class CookingMethod
{
private string Food;
private CookStrategy _cookStrategy;

public void SetCookStrategy(CookStrategy cookStrategy)


{
this._cookStrategy = cookStrategy;
}

public void SetFood(string name)


{
Food = name;
}

public void Cook()


{
_cookStrategy.Cook(Food);
Console.WriteLine();
}
}

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).

static void Main(string[] args)


{
CookingMethod cookMethod = new CookingMethod();

Console.WriteLine("What food would you like to cook?");


var food = Console.ReadLine();
cookMethod.SetFood(food);

Console.WriteLine("What cooking strategy would you like to use (1-3)?");


int input = int.Parse(Console.ReadKey().KeyChar.ToString());

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.

• The Strategy pattern decides on an appropriate behavior based


on external (relative to the object) inputs, whereas the State pattern decides
on an appropriate behavior based on the object's internal state.
• Objects in the State pattern store a reference to the object that is in that state;
no such thing occurs when using Strategy.
• Strategies (generally) handle only a single, specific task, whereas States can
be as complex as necessary to properly represent the desired state of an
object.

WILL I EVER USE THIS PATTERN?


Probably. I find this pattern to be very useful when refactoring applications which
have many different rules regarding how objects behave, particularly in our line-of-
business apps which often have many different possible strategies in play. If you're
only ever going to have two or three strategies for a given object, refactoring to the
Strategy pattern may not be worth it, but if you could possibly have more, that's
where this design pattern shines.

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.

DAY 16: THE PROXY DESIGN PATTERN


The Proxy design pattern provides a surrogate or placeholder object to control access
to another, different object. The Proxy object can be used in the same manner as its
containing object.

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

• Example Code: On GitHub

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:

• Take the patron's order.


• Deliver the patron's order.
• Process the diner's payment.

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 let's create a concrete Server class (the RealSubject participant):

// The RealSubject class which the Proxy can stand in for


class Server : IServer
{
private string Order;
public void TakeOrder(string order)
{
Console.WriteLine("Server takes order for " + order + ".");
Order = order;
}

public string DeliverOrder()


{
return Order;
}

public void ProcessPayment(string payment)


{
Console.WriteLine("Payment for order ("
+ payment + ") processed.");
}
}

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();

public void TakeOrder(string order)


{
Console.WriteLine("New trainee server takes order for "
+ order + ".");
Order = order;
}

public string DeliverOrder()


{
return Order;
}

public void ProcessPayment(string payment)


{
Console.WriteLine("New trainee cannot process payments yet!")
_server.ProcessPayment(payment);
}
}

As you can see, the NewServerProxy implements its


own TakeOrder() and DeliverOrder() methods, and calls
the Server class's ProcessPayment() method. Since they both implement IServer,
the NewServerProxy can be used any place the Server can be used.

WILL I EVER USE THIS PATTERN?


Almost definitely. If you've ever had a need to change the behavior of an existing
object without actually changing the definition of that object, the Proxy pattern can
allow you to do that. Further, I can see this being very useful in testing scenarios,
where you might need to replicate a class's behavior without fully implementing it.

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.

DAY 17: THE DECORATOR DESIGN PATTERN


As we work our way through the back half of the Gang of Four’s design patterns, we
now come to a pattern that you have almost certainly used, but may never have
implemented yourself: Decorator.

The Decorator design pattern seeks to add new functionality to an existing object
without changing that object's definition.

In other words, it wants to add new responsibilities to an individual instance of an


object, without adding those responsibilities to the class of objects. Decorator can be
thought of as an alternative to inheritance.

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.

The idea of our


restaurant is that we
only make dishes from
ingredients that are
available from our
farm; that is, we can
only make things from
the crops that we
grow. Further,
sometimes we get a
rush on particular
dishes, and when this
happens, we
occasionally need to
stop selling particular
dishes until we can
harvest more ingredients (after all, veggies don't grow overnight). In that scenario,
then, we need to be able to mark certain dishes as "sold out" once we run out of
ingredients.

Got all that? Let’s start the demo!

To model this farm-to-table restaurant, let's first define our Component participant,
which is a RestaurantDish abstract class:

/// The Component abstract class


abstract class RestaurantDish
{
public abstract void Display();
}

We also need a couple ConcreteComponent participant classes representing the


individual dishes we serve. These classes only implement their properties, not the
number of dishes available (which is the responsibility of the Decorator).

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;

public FreshSalad(string greens, string cheese, string dressing)


{
_greens = greens;
_cheese = cheese;
_dressing = dressing;
}

public override void Display()


{
Console.WriteLine("\nFresh Salad:");
Console.WriteLine(" Greens: {0}", _greens);
Console.WriteLine(" Cheese: {0}", _cheese);
Console.WriteLine(" Dressing: {0}", _dressing);
}
}

// A ConcreteComponent class
class Pasta : RestaurantDish
{
private string _pastaType;
private string _sauce;

public Pasta(string pastaType, string sauce)


{
_pastaType = pastaType;
_sauce = sauce;
}

public override void Display()


{
Console.WriteLine("\nClassic Pasta:");
Console.WriteLine(" Pasta: {0}", _pastaType);
Console.WriteLine(" Sauce: {0}", _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

// The abstract Decorator class.


abstract class Decorator : RestaurantDish
{
protected RestaurantDish _dish;

public Decorator(RestaurantDish dish)


{
_dish = dish;
}

public override void Display()


{
_dish.Display();
}
}

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.

// A ConcreteDecorator. This class will impart "responsibilities" onto the


// dishes (e.g. whether or not those dishes have enough ingredients left to
// order them)
class Available : Decorator
{
public int NumAvailable { get; set; } //How many can we make?
protected List<string> customers = new List<string>();
public Available(RestaurantDish dish, int numAvailable) : base(dish)
{
NumAvailable = numAvailable;
}

public void OrderItem(string name)


{
if (NumAvailable > 0)
{
customers.Add(name);
NumAvailable--;
}
else
{
Console.WriteLine("\nNot enough ingredients for "
+ name + "'s order!");
}
}

public override void Display()


{
base.Display();

foreach(var customer in customers)


{
Console.WriteLine("Ordered by " + customer);
}
}
}

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

static void Main(string[] args)


{
//Step 1: Define some dishes, and how many of each we can make
FreshSalad caesarSalad = new FreshSalad("Crisp romaine lettuce",
"Freshly-grated Parmesan cheese", "House-made Caesar dressing");
caesarSalad.Display();

Pasta fettuccineAlfredo = new Pasta("Fresh-made daily pasta",


"Creamy garlic alfredo sauce");
fettuccineAlfredo.Display();

Console.WriteLine("\nMaking these dishes available.");

//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);

//Step 3: Order a bunch of dishes


caesarAvailable.OrderItem("John");
caesarAvailable.OrderItem("Sally");
caesarAvailable.OrderItem("Manush");

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

ingredients. In this way, we have used


the Decorator pattern to help us keep
track of which dishes our farm-to-table
restaurant is able to server at any given
time.

WILL I EVER USE THIS PATTERN?


Possibly. You have most likely used this
pattern before, particularly if, like I am,
you are primarily a C#/ASP.NET
developer and work in web technologies.
In that case, you’ve almost certainly
used attributes like [Required] or
[Description], and those are examples of
the decorator pattern.

You may even need to implement this


pattern some day to solve a problem.
When you do, and as with all patterns,
keep in mind what problem the
Decorator design pattern is supposed to
solve.

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).

Now, I’m still hungry.


Where’d that salad I
ordered get to? Oh, finally!
Excuse me while I eat my
lunch.

Page 106
Matthew P Jones The Daily Design Pattern

DAY 18: CHAIN OF RESPONSIBILITY DESIGN PATTERN


We are now starting to deal with more complex design patterns, which in turn solve
more complex problems. One of these is Chain of Responsibility.

The Chain of Responsibility design pattern seeks to avoid coupling a request to a


particular receiver by giving more than one object a chance to handle a particular
request.

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.

There's a hierarchy in play here:


Head Chef > Purchasing
Manager > General Manager.
We can model this purchasing
system using the Chain of
Responsibility design pattern.

First, let's model the object that


represents the purchase order
itself.

// The details of the purchase request.


class PurchaseOrder
{
public PurchaseOrder(int number, double amount,
double price, string name)
{
RequestNumber = number;
Amount = amount;
Price = price;
Name = name;

Console.WriteLine("Purchase request for " + name + " ("


+ amount + " for $" + price.ToString() + ") has been submitted.");
}

public int RequestNumber { get; set; }


public double Amount { get; set; }
public double Price { get; set; }
public string Name { get; set; }
}

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;

public void SetSupervisor(Approver supervisor)


{
this.Supervisor = supervisor;
}

public abstract void ProcessRequest(PurchaseOrder purchase);


}

Now we can implement our ConcreteHandler objects: one for each person in the
chain.

// A concrete Handler class


class HeadChef : Approver
{
public override void ProcessRequest(PurchaseOrder purchase)
{
if (purchase.Price < 1000)
{
Console.WriteLine("{0} approved purchase request #{1}",
this.GetType().Name, purchase.RequestNumber);
}
else if (Supervisor != null)
{
Supervisor.ProcessRequest(purchase);
}
}
}

Page 109
Matthew P Jones The Daily Design Pattern

// A concrete Handler class


class PurchasingManager : Approver
{
public override void ProcessRequest(PurchaseOrder purchase)
{
if (purchase.Price < 2500)
{
Console.WriteLine("{0} approved purchase request #{1}",
this.GetType().Name, purchase.RequestNumber);
}
else if (Supervisor != null)
{
Supervisor.ProcessRequest(purchase);
}
}
}

// A concrete Handler class


class GeneralManager : Approver
{
public override void ProcessRequest(PurchaseOrder purchase)
{
if (purchase.Price < 10000)
{
Console.WriteLine("{0} approved purchase request #{1}",
this.GetType().Name, purchase.RequestNumber);
}
else
{
Console.WriteLine(
"Purchase request #{0} requires an executive
meeting!", purchase.RequestNumber);
}
}
}

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.

static void Main(string[] args)


{
//Create the chain links
Approver jennifer = new HeadChef();
Approver mitchell = new PurchasingManager();
Approver olivia = new GeneralManager();

//Create the chain


jennifer.SetSupervisor(mitchell);
mitchell.SetSupervisor(olivia);

// Generate and process purchase requests


PurchaseOrder p = new PurchaseOrder(1, 20, 69, "Spices");
jennifer.ProcessRequest(p);

p = new PurchaseOrder(2, 300, 1389, "Fresh Veggies");


jennifer.ProcessRequest(p);

p = new PurchaseOrder(3, 500, 4823.99, "Beef");


jennifer.ProcessRequest(p);

p = new PurchaseOrder(4, 4, 12099, "Ovens");


jennifer.ProcessRequest(p);

// Wait for user


Console.ReadKey();
}

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.

The output of this sample


project looks like the
screenshot on the right.
Each request flows through
the chain until a link
handles it. That's the
definition of the Chain of
Responsibility Design
Pattern!

Page 111
Matthew P Jones The Daily Design Pattern

WILL I EVER USE THIS PATTERN?


Rarely. I personally haven't used it at all, but I can see why it would be useful in
situations where there's a hierarchy of objects and each one could handle a particular
request. But, as always, I'd love to hear about real-world uses of this pattern, so feel
free to let me know!

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!

DAY 19: THE VISITOR DESIGN PATTERN


The Visitor design pattern lets us operate on objects by representing that operation
as an object unto itself. Thereby, we can operate on said objects without changing
the classes or definitions of those objects.

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

• The ObjectStructure can


enumerate its elements and
may provide a high-level
interface to allow the Visitor to
visit its elements.

A DELICIOUS EXAMPLE
To model the Visitor design pattern,
let's talk about a very successful
restaurant and the employees who
work there.

In this scenario, our family-run


restaurant has been, to put it
lightly, killing it. We're full to capacity
every day, customers rave about our
menu, critics love our decor and our
staff are the most professional and
responsive employees in the county;
in short, we're the best dang
restaurant in the city.

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.

// The ConcreteElement class implements all operations defined by Element.


class Employee : Element
{
public string Name { get; set; }
public double AnnualSalary { get; set; }
public int PaidTimeOffDays { get; set; }

public Employee(string name, double annualSalary, int paidTimeOffDays)


{
Name = name;
AnnualSalary = annualSalary;
PaidTimeOffDays = paidTimeOffDays;
}

public override void Accept(IVisitor visitor)


{
visitor.Visit(this);
}
}

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.

// The Visitor interface, which declares a Visit operation for each


// ConcreteVisitor to implement.
interface IVisitor
{
void Visit(Element element);
}

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.

// A Concrete Visitor class.


class IncomeVisitor : IVisitor
{
public void Visit(Element element)
{
Employee employee = element as Employee;

// We've had a great year, so 10% pay raises for everyone!


employee.AnnualSalary *= 1.10;
Console.WriteLine("{0} {1}'s new income: {2:C}",
employee.GetType().Name, employee.Name, employee.AnnualSalary);
}
}

// A Concrete Visitor class


class PaidTimeOffVisitor : IVisitor
{
public void Visit(Element element)
{
Employee employee = element as Employee;

// 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

To complete the pattern, we need classes to represent all of our employees as a


group and individually. The aggregate collection of employees is
our ObjectStructure participant, the example code for which is on the next page.

class Employees
{
private List<Employee> _employees = new List<Employee>();

public void Attach(Employee employee)


{
_employees.Add(employee);
}

public void Detach(Employee employee)


{
_employees.Remove(employee);
}

public void Accept(IVisitor visitor)


{
foreach (Employee e in _employees)
{
e.Accept(visitor);
}
Console.WriteLine();
}
}

class LineCook : Employee


{
public LineCook() : base("Dmitri", 32000, 7) { }
}

class HeadChef : Employee


{
public HeadChef() : base("Jackson", 69015, 21) { }
}

class GeneralManager : Employee


{
public GeneralManager() : base("Amanda", 78000, 24) { }
}

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:

static void Main(string[] args)


{
// Who are my employees?
Employees e = new Employees();
e.Attach(new LineCook());
e.Attach(new HeadChef());
e.Attach(new GeneralManager());

// Employees are visited, giving them 10% raises


// and 3 extra paid time off days.
e.Accept(new IncomeVisitor());
e.Accept(new PaidTimeOffVisitor());

Console.ReadKey();
}

Running the sample app


produces the output similar
to the screenshot shown to
the right.

In short, we created two


visitors (IncomeVisitor and
PaidTimeOffVisitor) which
visited each Employee record
and modified their internal
states before vanishing like a thief in the night. And all of our employees are surely
happy with the new money and time we've given them.

WILL I EVER USE THIS PATTERN?


Probably not, at least not for simple projects. To be honest, I'm tempted to
think of this pattern as being the Burglar pattern rather than the Visitor pattern,
since it consists of some heretofore unknown instance of an object showing up,
breaking in, rearranging things, and vanishing without a trace.

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.

DAY 20: THE COMPOSITE DESIGN PATTERN


Only three daily design patterns left! Let’s keep going!

The next pattern we are going to demo is one that can make a complicated hierarchy
structure much simpler to implement: Composite.

The Composite design pattern represents part-whole hierarchies of objects. "Part-


whole hierarchies" is a really fancy way of saying you can represent all or part of a
hierarchy by reducing the pieces in said hierarchy down to common components.

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

• The Composite defines


behavior for components
which have children
(contrasting the Leaves). It
also stores its child
components and implements
the add/remove children
interface from the
Component.
• The Client manipulates
objects in the composition
through the Component
interface.

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.

For those of you that haven't seen


these monstrosities, they're not at
all like the regular soda dispensers
you'll find at restaurants. The
regular dispenses have six, or
eight, or maybe twelve flavors; the
Freestyle machines have
potentially hundreds. Any flavor of
drink that the Coca-Cola company
makes in your part of the world,
you can order at this machine.

The most interesting part of this


device, though, is its interface. The
Freestyle wants you to "drill-down"
by first selecting a brand (e.g.
Coke, Fanta, Sprite, Dasani, etc.)
and then selecting a flavor (e.g.
Cherry, Vanilla, etc.). In effect,
this creates a hierarchy where
"Soda" itself is the root
Component; the brands are the
child Components, and the flavors
are Leaves.

A simplified version of this object


hierarchy might look like this:

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

public abstract class SoftDrink


{
public int Calories { get; set; }

public List<SoftDrink> Flavors { get; set; }

public SoftDrink(int calories)


{
Calories = calories;
Flavors = new List<SoftDrink>();
}

// "Flatten" method, returns all available flavors


public void DisplayCalories()
{
Console.WriteLine(this.GetType().Name + ": " +
this.Calories.ToString() + " calories.");
foreach (var drink in this.Flavors)
drink.DisplayCalories();
}
}

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.

We now need to implement the Composite participant, which represents objects in


the hierarchy which have children. For our decision tree, we have two
Composites: Colas and RootBeers.

// 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.

// Composite class, root node


public class SodaWater : SoftDrink
{
public SodaWater(int calories) : base(calories) { }
}

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.

static void Main(string[] args)


{
var colas = new Cola(210);
colas.Flavors.Add(new VanillaCola(215));
colas.Flavors.Add(new CherryCola(210));

var lemonLime = new LemonLime(185);

var rootBeers = new RootBeer(195);


rootBeers.Flavors.Add(new VanillaRootBeer(200));
rootBeers.Flavors.Add(new StrawberryRootBeer(200));

SodaWater sodaWater = new SodaWater(180);


sodaWater.Flavors.Add(colas);
sodaWater.Flavors.Add(lemonLime);
sodaWater.Flavors.Add(rootBeers);

sodaWater.DisplayCalories();

Console.ReadKey();
}

Page 123
Matthew P Jones The Daily Design Pattern

The output of this code is shown in


the screenshot to the right.

Well done! We have now used the


Composite design pattern to model
a hierarchy and treat every “node”
in this hierarchy as the same kind of
object!

WILL I EVER USE THIS PATTERN?


Will you ever have hierarchical data? If so, probably yes. The key part of this pattern
is that you can treat different nodes in the hierarchy as the same, provided you set
up the appropriate interfaces and abstracts.

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.)

DAY 21: THE MEDIATOR DESIGN PATTERN


For our second-to-last daily design pattern, we’re going to demo Mediator.

The Mediator design pattern defines an object which encapsulates how a set of
objects interact with each other.

You can think of a Mediator object as a kind of traffic-coordinator; it directs traffic to


appropriate parties based on its own state or outside values. Further, Mediator
promotes loose coupling (a good thing!) by keeping objects from referring to each
other explicitly.

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.

• The ConcreteMediator classes implement behavior to coordinate Colleague


objects. Each ConcreteMediator knows what its constituent Colleague classes
are.

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.

// The Colleague abstract class, representing an entity involved in the


// conversation which should receive messages.
abstract class ConcessionStand
{
protected Mediator mediator;

public ConcessionStand(Mediator mediator)


{
this.mediator = mediator;
}
}

We can now implement the ConcreteColleague participants, which represent each


snack bar in the theatre. In this case, we'll pretend our movie theatre has two
snack bars: one in the northern part of the theatre and one in the southern part.
The example code for this is on the next page.

Page 126
Matthew P Jones The Daily Design Pattern

class NorthConcessionStand : ConcessionStand


{
public NorthConcessionStand(Mediator mediator) : base(mediator) { }

public void Send(string message)


{
Console.WriteLine("North Concession Stand sends message: "
+ message);
mediator.SendMessage(message, this);
}

public void Notify(string message)


{
Console.WriteLine("North Concession Stand gets message: "
+ message);
}
}

class SouthConcessionStand : ConcessionStand


{
public SouthConcessionStand(Mediator mediator) : base(mediator) { }

public void Send(string message)


{
Console.WriteLine("South Concession Stand sends message: "
+ message);
mediator.SendMessage(message, this);
}

public void Notify(string message)


{
Console.WriteLine("South Concession Stand gets message: " + message);
}
}

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;

public NorthConcessionStand NorthConcessions


{
set { _northConcessions = value; }
}

public SouthConcessionStand SouthConcessions


{
set { _southConcessions = value; }
}

public void SendMessage(string message, ConcessionStand colleague)


{
if (colleague == _northConcessions)
{
_southConcessions.Notify(message);
}
else
{
_northConcessions.Notify(message);
}
}
}

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:

static void Main(string[] args)


{
ConcessionsMediator mediator = new ConcessionsMediator();

NorthConcessionStand leftKitchen = new NorthConcessionStand(mediator);


SouthConcessionStand rightKitchen = new SouthConcessionStand(mediator);

mediator.NorthConcessions = leftKitchen;
mediator.SouthConcessions = rightKitchen;

leftKitchen.Send("Can you send some popcorn?");


rightKitchen.Send("Sure thing, Kenny's on his way.");

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.

WILL I EVER USE THIS PATTERN?


Maybe. The scenarios in which it is useful often seem like solved problems: chat
systems and similar things. But considering how often tech likes to reinvent itself, I
wouldn’t be surprised if you, dear reader, needed this pattern at some point in your
career.

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.

DAY 22: THE COMMAND DESIGN PATTERN


Welcome to the last day of the Daily Design Pattern series, and congratulations on
making it this far! For today’s exercise, let’s discuss the only remaining pattern in the
Gang of Four book: Command.

The Command design pattern encapsulates a request as an object, thereby allowing


us developers to treat that request differently based upon what class receives said
command. Further, it enables much more complex architectures, and even enables
operations such as undo/redo.

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.

For that sample project,


and in keeping with the
food theme we’ve been
using throughout this
book, we’re going to
model a system in
which we can create an
order for a fast food
restaurant, as well as
add, remove, and
modify items in the
order using Command.

To begin building our


demo, let's first create a
class which
represents an item PHOTO BY JONATHAN BORBA / UNSPLASH
being ordered.

// Represents an item being ordered from this restaurant.


public class MenuItem
{
public string Name { get; set; }
public int Amount { get; set; }
public double Price { get; set; }

public MenuItem(string name, int amount, double price)


{
Name = name;
Amount = amount;
Price = price;
}

public void Display()


{
Console.WriteLine("\nName: " + Name);
Console.WriteLine("Amount: " + Amount.ToString());
Console.WriteLine("Price: $" + Price.ToString());
}
}

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:

// The Invoker class


public class Patron
{
private OrderCommand _orderCommand;
private MenuItem _menuItem;
private FastFoodOrder _order;

public Patron()
{ _order = new FastFoodOrder(); }

public void SetCommand(int commandOption)


{ _orderCommand = new CommandFactory().GetCommand(commandOption); }

public void SetMenuItem(MenuItem item)


{ _menuItem = item; }

public void ExecuteCommand()


{ _order.ExecuteCommand(_orderCommand, _menuItem); }

public void ShowCurrentOrder()


{ _order.ShowCurrentItems(); }
}

public class CommandFactory


{
//Factory method
public OrderCommand GetCommand(int commandOption)
{
switch (commandOption)
{
case 1:
return new AddCommand();
case 2:
return new ModifyCommand();
case 3:
return new RemoveCommand();
default:
return new AddCommand();
}
}
}

Page 132
Matthew P Jones The Daily Design Pattern

Note that the Patron keeps a reference to an instance of FastFoodOrder, which is


our Receiver participant and is implemented like so:

// The Receiver
public class FastFoodOrder
{
public List<MenuItem> currentItems { get; set; }
public FastFoodOrder()
{
currentItems = new List<MenuItem>();
}

public void ExecuteCommand(OrderCommand command, MenuItem item)


{
command.Execute(this.currentItems, item);
}

public void ShowCurrentItems()


{
foreach(var item in currentItems)
{
item.Display();
}
Console.WriteLine("-----------------------");
}
}

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.

Speaking of the commands, let’s implement the base Command participant:

// The Command abstract class


public abstract class OrderCommand
{
public abstract void Execute(List<MenuItem> order, MenuItem newItem);
}

Page 133
Matthew P Jones The Daily Design Pattern

Now we can also implement several ConcreteCommand participant objects:

// 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

static void Main(string[] args)


{
Patron patron = new Patron();
patron.SetCommand(1 /*Add*/);
patron.SetMenuItem(new MenuItem("French Fries", 2, 1.99));
patron.ExecuteCommand();

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();

//Remove the french fries


patron.SetCommand(3 /*Remove*/);
patron.SetMenuItem(new MenuItem("French Fries", 2, 1.99));
patron.ExecuteCommand();

patron.ShowCurrentOrder();

//Now we want 4 hamburgers rather than 2


patron.SetCommand(2 /*Edit*/);
patron.SetMenuItem(new MenuItem("Hamburger", 4, 2.59));
patron.ExecuteCommand();

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

WILL I EVER USE THIS PATTERN?


Once you start dealing with more complex
architectures, then yes, most likely you
will need the Command design pattern at
some point. This is an extremely useful
pattern, but it brings some complexity
along with it.

As with all design patterns, make sure you


need to solve the problem the pattern is
designed to solve and are willing to invoke
the extra complexity before you decide to
use a 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

DAY 23: WRAPPING UP


Thank you so much for reading my eBook! I really appreciate your support for my
projects on Exception Not Found, and I hope this book is a sufficient token of my
thanks.

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.

And, as always: Happy Coding!

Page 137

You might also like