Design-Pattern Text Book
Design-Pattern Text Book
An Introduction to
Design Patterns
(C#, WPF, ASP.NET, AJAX, PATTERNS)
Formatted By-
Ashish Tripathi
Email: [email protected]
Note: All the contents present into the book is extracted from the site
http://www.dofactory.com/Patterns/Patterns.aspx without any textual change only
formatting and presentation of the text is changed. For any genuine change in the book
you can ask for the editable copy of the book by sending a mail to
[email protected] with subject line ‘Design Patterns’
****** 1
For more informations visit http://www.dofactory.com/Patterns/Patterns.aspx
An Introduction to Design Patterns
Design Patterns...........................................................................................................3
1. Introduction...................................................................................................3
2. Type of Design Patterns ..................................................................................4
2.1 Creational Patterns .............................................................................4
2.2 Structural Patterns .............................................................................4
2.3 Behavioral Patterns.............................................................................4
3. Creational Design Patterns .............................................................................5
3.1 Abstract Factory Design Pattern ..........................................................5
3.2 Builder Design Pattern ......................................................................11
3.3 Factory Method Design Pattern..........................................................18
3.4 Prototype Design Pattern ...................................................................23
3.5 Singleton Design Pattern ...................................................................28
4. Structural Design Patterns ...........................................................................32
4.1 Adapter Design Pattern .....................................................................32
4.2 Bridge Design Pattern .......................................................................37
4.3 Composite Design Pattern .................................................................43
4.4 Decorator Design Pattern ..................................................................49
4.5 Facade Design Pattern ......................................................................55
4.6 Flyweight Design Pattern...................................................................60
4.7 Proxy Design Pattern.........................................................................66
5. Behavioral Design Patterns...........................................................................70
5.1 Chain of Responsibility Design pattern ..............................................70
5.2 Command Design Pattern..................................................................76
5.3 Interpreter Design Pattern .................................................................82
5.4 Iterator Design pattern ......................................................................87
5.5 Mediator Design Pattern....................................................................94
5.6 Memento Design Pattern .................................................................100
5.7 Observer Design Pattern..................................................................106
5.8 State Design Pattern .......................................................................112
5.9 Strategy Design Pattern...................................................................120
5.10 Template Method Design Pattern ...................................................125
5.11 Visitor Design Pattern ...................................................................130
****** 2
For more informations visit http://www.dofactory.com/Patterns/Patterns.aspx
An Introduction to Design Patterns
Design Patterns
1. Introduction
Design patterns are recurring solutions to software design problems
you find again and again in real-world application development.
Patterns are about design and interaction of objects, as well as
providing a communication platform concerning elegant, reusable
solutions to commonly encountered programming challenges.
The Gang of Four (GoF) patterns are generally considered the foundation for all other
patterns. They are categorized in three groups: Creational, Structural, and Behavioral.
Here you will find information on these important patterns.
To give you a head start, the C# source code is provided in 2 forms: 'structural' and
'real-world'. Structural code uses type names as defined in the pattern definition and
UML diagrams. Real-world code provides real-world programming situations where you
may use these patterns.
A third form, '.NET optimized' demonstrates design patterns that exploit built-in .NET
2.0 features, such as, generics, attributes, delegates, and reflection. These and much
more are available in our Design Pattern Framework 2.0TM. See our Singleton page for a
.NET 2.0 Optimized code sample.
****** 3
For more informations visit http://www.dofactory.com/Patterns/Patterns.aspx
An Introduction to Design Patterns
****** 4
For more informations visit http://www.dofactory.com/Patterns/Patterns.aspx
An Introduction to Design Patterns
3.1.1 Definition
Provide an interface for creating families of related or dependent objects
without specifying their concrete classes.
****** 5
For more informations visit http://www.dofactory.com/Patterns/Patterns.aspx
An Introduction to Design Patterns
using System;
namespace DoFactory.GangOfFour.Abstract.Structural
{
// MainApp test application
class MainApp
{
public static void Main()
{
// Abstract factory #1
AbstractFactory factory1 = new ConcreteFactory1();
Client c1 = new Client(factory1);
c1.Run();
// Abstract factory #2
AbstractFactory factory2 = new ConcreteFactory2();
Client c2 = new Client(factory2);
c2.Run();
// "AbstractFactory"
// "ConcreteFactory1"
****** 6
For more informations visit http://www.dofactory.com/Patterns/Patterns.aspx
An Introduction to Design Patterns
{
return new ProductB1();
}
}
// "ConcreteFactory2"
// "AbstractProductA"
// "AbstractProductB"
// "ProductA1"
// "ProductB1"
// "ProductA2"
****** 7
For more informations visit http://www.dofactory.com/Patterns/Patterns.aspx
An Introduction to Design Patterns
// "ProductB2"
class Client
{
private AbstractProductA AbstractProductA;
private AbstractProductB AbstractProductB;
// Constructor
public Client(AbstractFactory factory)
{
AbstractProductB = factory.CreateProductB();
AbstractProductA = factory.CreateProductA();
}
Output
ProductB1 interacts with ProductA1
ProductB2 interacts with ProductA2
This real-world code demonstrates the creation of different animal worlds for a
computer game using different factories. Although the animals created by the Continent
factories are different, the interactions among the animals remain the same.
using System;
namespace DoFactory.GangOfFour.Abstract.RealWorld
{
// MainApp test application
class MainApp
{
public static void Main()
{
****** 8
For more informations visit http://www.dofactory.com/Patterns/Patterns.aspx
An Introduction to Design Patterns
// "AbstractFactory"
// "ConcreteFactory1"
// "ConcreteFactory2"
// "AbstractProductA"
****** 9
For more informations visit http://www.dofactory.com/Patterns/Patterns.aspx
An Introduction to Design Patterns
{
}
// "AbstractProductB"
// "ProductA1"
// "ProductB1"
// "ProductA2"
// "ProductB2"
// "Client"
class AnimalWorld
{
private Herbivore herbivore;
private Carnivore carnivore;
// Constructor
****** 10
For more informations visit http://www.dofactory.com/Patterns/Patterns.aspx
An Introduction to Design Patterns
3.2.1 Definition
Separate the construction of a complex object from its representation so
that the same construction process can create different representations.
****** 11
For more informations visit http://www.dofactory.com/Patterns/Patterns.aspx
An Introduction to Design Patterns
using System;
using System.Collections;
namespace DoFactory.GangOfFour.Builder.Structural
{
// MainApp test application
director.Construct(b2);
Product p2 = b2.GetResult();
p2.Show();
// "Director"
class Director
{
// Builder uses a complex series of steps
public void Construct(Builder builder)
{
builder.BuildPartA();
builder.BuildPartB();
}
}
// "Builder"
****** 12
For more informations visit http://www.dofactory.com/Patterns/Patterns.aspx
An Introduction to Design Patterns
// "ConcreteBuilder1"
// "ConcreteBuilder2"
// "Product"
class Product
{
ArrayList parts = new ArrayList();
****** 13
For more informations visit http://www.dofactory.com/Patterns/Patterns.aspx
An Introduction to Design Patterns
Output
Product Parts -------
PartA
PartB
This real-world code demonstates the Builder pattern in which different vehicles are
assembled in a step-by-step fashion. The Shop uses VehicleBuilders to construct a
variety of Vehicles in a series of sequential steps.
using System;
using System.Collections;
namespace DoFactory.GangOfFour.Builder.RealWorld
{
// MainApp test application
shop.Construct(b2);
b2.Vehicle.Show();
****** 14
For more informations visit http://www.dofactory.com/Patterns/Patterns.aspx
An Introduction to Design Patterns
shop.Construct(b3);
b3.Vehicle.Show();
// "Director"
class Shop
{
// Builder uses a complex series of steps
public void Construct(VehicleBuilder vehicleBuilder)
{
vehicleBuilder.BuildFrame();
vehicleBuilder.BuildEngine();
vehicleBuilder.BuildWheels();
vehicleBuilder.BuildDoors();
}
}
// "Builder"
// Property
public Vehicle Vehicle
{
get{ return vehicle; }
}
// "ConcreteBuilder1"
****** 15
For more informations visit http://www.dofactory.com/Patterns/Patterns.aspx
An Introduction to Design Patterns
// "ConcreteBuilder2"
// "ConcreteBuilder3"
****** 16
For more informations visit http://www.dofactory.com/Patterns/Patterns.aspx
An Introduction to Design Patterns
// "Product"
class Vehicle
{
private string type;
private Hashtable parts = new Hashtable();
// Constructor
public Vehicle(string type)
{
this.type = type;
}
Output
---------------------------
Vehicle Type: Scooter
Frame : Scooter Frame
Engine : none
#Wheels: 2
#Doors : 0
---------------------------
Vehicle Type: Car
Frame : Car Frame
****** 17
For more informations visit http://www.dofactory.com/Patterns/Patterns.aspx
An Introduction to Design Patterns
Engine : 2500 cc
#Wheels: 4
#Doors : 4
---------------------------
Vehicle Type: MotorCycle
Frame : MotorCycle Frame
Engine : 500 cc
#Wheels: 2
#Doors : 0
3.3.1 Definition
Define an interface for creating an object, but let subclasses decide
which class to instantiate. Factory Method lets a class defer
instantiation to subclasses.
****** 18
For more informations visit http://www.dofactory.com/Patterns/Patterns.aspx
An Introduction to Design Patterns
using System;
using System.Collections;
namespace DoFactory.GangOfFour.Factory.Structural
{
class MainApp
{
static void Main()
{
// An array of creators
Creator[] creators = new Creator[2];
creators[0] = new ConcreteCreatorA();
creators[1] = new ConcreteCreatorB();
// "Product"
// "ConcreteProductA"
// "ConcreteProductB"
****** 19
For more informations visit http://www.dofactory.com/Patterns/Patterns.aspx
An Introduction to Design Patterns
// "Creator"
// "ConcreteCreator"
// "ConcreteCreator"
Output
Created ConcreteProductA
Created ConcreteProductB
This real-world code demonstrates the Factory method offering flexibility in creating
different documents. The derived Document classes Report and Resume instantiate
extended versions of the Document class. Here, the Factory Method is called in the
constructor of the Document base class.
using System;
using System.Collections;
namespace DoFactory.GangOfFour.Factory.RealWorld
{
class MainApp
{
static void Main()
{
// Note: constructors call Factory Method
Document[] documents = new Document[2];
****** 20
For more informations visit http://www.dofactory.com/Patterns/Patterns.aspx
An Introduction to Design Patterns
// "Product"
// "ConcreteProduct"
// "ConcreteProduct"
// "ConcreteProduct"
// "ConcreteProduct"
// "ConcreteProduct"
****** 21
For more informations visit http://www.dofactory.com/Patterns/Patterns.aspx
An Introduction to Design Patterns
// "ConcreteProduct"
// "ConcreteProduct"
// "ConcreteProduct"
// "Creator"
// Factory Method
public abstract void CreatePages();
}
// "ConcreteCreator"
// "ConcreteCreator"
****** 22
For more informations visit http://www.dofactory.com/Patterns/Patterns.aspx
An Introduction to Design Patterns
Output
Resume -------
SkillsPage
EducationPage
ExperiencePage
Report -------
IntroductionPage
ResultsPage
ConclusionPage
SummaryPage
BibliographyPage
****** 23
For more informations visit http://www.dofactory.com/Patterns/Patterns.aspx
An Introduction to Design Patterns
using System;
namespace DoFactory.GangOfFour.Prototype.Structural
{
class MainApp
{
// "Prototype"
// Constructor
public Prototype(string id)
{
this.id = id;
}
// Property
****** 24
For more informations visit http://www.dofactory.com/Patterns/Patterns.aspx
An Introduction to Design Patterns
public string Id
{
get{ return id; }
}
// "ConcretePrototype1"
// "ConcretePrototype2"
Output
Cloned: I
Cloned: II
This real-world code demonstrates the Prototype pattern in which new Color objects are
created by copying pre-existing, user-defined Colors of the same type.
using System;
using System.Collections;
****** 25
For more informations visit http://www.dofactory.com/Patterns/Patterns.aspx
An Introduction to Design Patterns
namespace DoFactory.GangOfFour.Prototype.RealWorld
{
class MainApp
{
static void Main()
{
ColorManager colormanager = new ColorManager();
Color color;
name = "peace";
color = colormanager[name].Clone() as Color;
name = "flame";
color = colormanager[name].Clone() as Color;
// "Prototype"
// "ConcretePrototype"
// Constructor
****** 26
For more informations visit http://www.dofactory.com/Patterns/Patterns.aspx
An Introduction to Design Patterns
// Prototype manager
class ColorManager
{
Hashtable colors = new Hashtable();
// Indexer
public ColorPrototype this[string name]
{
get
{
return colors[name] as ColorPrototype;
}
set
{
colors.Add(name, value);
}
}
}
}
Output
Cloning color RGB: 255, 0, 0
Cloning color RGB: 128,211,128
Cloning color RGB: 211, 34, 2
****** 27
For more informations visit http://www.dofactory.com/Patterns/Patterns.aspx
An Introduction to Design Patterns
using System;
namespace DoFactory.GangOfFour.Singleton.Structural
{
class MainApp
{
if (s1 == s2)
{
Console.WriteLine("Objects are the same instance");
}
// "Singleton"
****** 28
For more informations visit http://www.dofactory.com/Patterns/Patterns.aspx
An Introduction to Design Patterns
class Singleton
{
private static Singleton instance;
return instance;
}
}
}
Output
Objects are the same instance
using System;
using System.Collections;
using System.Threading;
namespace DoFactory.GangOfFour.Singleton.RealWorld
{
class MainApp
{
static void Main()
{
LoadBalancer b1 = LoadBalancer.GetLoadBalancer();
LoadBalancer b2 = LoadBalancer.GetLoadBalancer();
LoadBalancer b3 = LoadBalancer.GetLoadBalancer();
LoadBalancer b4 = LoadBalancer.GetLoadBalancer();
// Same instance?
if (b1 == b2 && b2 == b3 && b3 == b4)
****** 29
For more informations visit http://www.dofactory.com/Patterns/Patterns.aspx
An Introduction to Design Patterns
{
Console.WriteLine("Same instance\n");
}
// "Singleton"
class LoadBalancer
{
private static LoadBalancer instance;
private ArrayList servers = new ArrayList();
// Constructor (protected)
protected LoadBalancer()
{
// List of available servers
servers.Add("ServerI");
servers.Add("ServerII");
servers.Add("ServerIII");
servers.Add("ServerIV");
servers.Add("ServerV");
}
****** 30
For more informations visit http://www.dofactory.com/Patterns/Patterns.aspx
An Introduction to Design Patterns
return instance;
}
Output
Same instance
ServerIII
ServerII
ServerI
ServerII
ServerI
ServerIII
ServerI
ServerIII
ServerIV
ServerII
ServerII
ServerIII
ServerIV
ServerII
ServerIV
****** 31
For more informations visit http://www.dofactory.com/Patterns/Patterns.aspx
An Introduction to Design Patterns
using System;
namespace DoFactory.GangOfFour.Adapter.Structural
{
class MainApp
{
static void Main()
****** 32
For more informations visit http://www.dofactory.com/Patterns/Patterns.aspx
An Introduction to Design Patterns
{
// Create adapter and place a request
Target target = new Adapter();
target.Request();
// "Target"
class Target
{
public virtual void Request()
{
Console.WriteLine("Called Target Request()");
}
}
// "Adapter"
// "Adaptee"
class Adaptee
{
public void SpecificRequest()
{
Console.WriteLine("Called SpecificRequest()");
}
}
}
Output
Called SpecificRequest()
This real-world code demonstrates the use of a legacy chemical databank. Chemical
compound objects access the databank through an Adapter interface.
// Adapter pattern -- Real World example
****** 33
For more informations visit http://www.dofactory.com/Patterns/Patterns.aspx
An Introduction to Design Patterns
using System;
namespace DoFactory.GangOfFour.Adapter.RealWorld
{
class MainApp
{
static void Main()
{
// Non-adapted chemical compound
Compound stuff = new Compound("Unknown");
stuff.Display();
// "Target"
class Compound
{
protected string name;
protected float boilingPoint;
protected float meltingPoint;
protected double molecularWeight;
protected string molecularFormula;
// Constructor
public Compound(string name)
{
this.name = name;
}
// "Adapter"
****** 34
For more informations visit http://www.dofactory.com/Patterns/Patterns.aspx
An Introduction to Design Patterns
// Constructor
public RichCompound(string name) : base(name)
{
}
base.Display();
Console.WriteLine(" Formula: {0}", molecularFormula);
Console.WriteLine(" Weight : {0}", molecularWeight);
Console.WriteLine(" Melting Pt: {0}", meltingPoint);
Console.WriteLine(" Boiling Pt: {0}", boilingPoint);
}
}
// "Adaptee"
class ChemicalDatabank
{
// The Databank 'legacy API'
public float GetCriticalPoint(string compound, string point)
{
float temperature = 0.0F;
// Melting Point
if (point == "M")
{
switch (compound.ToLower())
{
case "water" : temperature = 0.0F; break;
case "benzene" : temperature = 5.5F; break;
case "alcohol" : temperature = -114.1F; break;
}
}
// Boiling Point
else
{
switch (compound.ToLower())
{
case "water" : temperature = 100.0F; break;
case "benzene" : temperature = 80.1F; break;
case "alcohol" : temperature = 78.3F; break;
}
****** 35
For more informations visit http://www.dofactory.com/Patterns/Patterns.aspx
An Introduction to Design Patterns
}
return temperature;
}
switch (compound.ToLower())
{
case "water" : structure = "H20"; break;
case "benzene" : structure = "C6H6"; break;
case "alcohol" : structure = "C2H6O2"; break;
}
return structure;
}
Output
Compound: Unknown ------
****** 36
For more informations visit http://www.dofactory.com/Patterns/Patterns.aspx
An Introduction to Design Patterns
using System;
namespace DoFactory.GangOfFour.Bridge.Structural
{
****** 37
For more informations visit http://www.dofactory.com/Patterns/Patterns.aspx
An Introduction to Design Patterns
class MainApp
{
static void Main()
{
Abstraction ab = new RefinedAbstraction();
// "Abstraction"
class Abstraction
{
protected Implementor implementor;
// Property
public Implementor Implementor
{
set{ implementor = value; }
}
// "Implementor"
// "RefinedAbstraction"
****** 38
For more informations visit http://www.dofactory.com/Patterns/Patterns.aspx
An Introduction to Design Patterns
}
}
// "ConcreteImplementorA"
// "ConcreteImplementorB"
Output
ConcreteImplementorA Operation
ConcreteImplementorB Operation
using System;
using System.Collections;
namespace DoFactory.GangOfFour.Bridge.RealWorld
{
class MainApp
{
static void Main()
{
// Create RefinedAbstraction
Customers customers =
new Customers("Chicago");
// Set ConcreteImplementor
customers.Data = new CustomersData();
****** 39
For more informations visit http://www.dofactory.com/Patterns/Patterns.aspx
An Introduction to Design Patterns
customers.ShowAll();
// "Abstraction"
class CustomersBase
{
private DataObject dataObject;
protected string group;
// Property
public DataObject Data
{
set{ dataObject = value; }
get{ return dataObject; }
}
****** 40
For more informations visit http://www.dofactory.com/Patterns/Patterns.aspx
An Introduction to Design Patterns
// "RefinedAbstraction"
// "Implementor"
// "ConcreteImplementor"
public CustomersData()
{
// Loaded from a database
customers.Add("Jim Jones");
****** 41
For more informations visit http://www.dofactory.com/Patterns/Patterns.aspx
An Introduction to Design Patterns
customers.Add("Samual Jackson");
customers.Add("Allen Good");
customers.Add("Ann Stills");
customers.Add("Lisa Giolani");
}
Output
Jim Jones
Samual Jackson
Allen Good
------------------------
Customer Group: Chicago
Jim Jones
****** 42
For more informations visit http://www.dofactory.com/Patterns/Patterns.aspx
An Introduction to Design Patterns
Samual Jackson
Allen Good
Ann Stills
Lisa Giolani
Henry Velasquez
------------------------
****** 43
For more informations visit http://www.dofactory.com/Patterns/Patterns.aspx
An Introduction to Design Patterns
4.3.3Sample code in C#
This structural code demonstrates the Composite pattern which allows the creation of a
tree structure in which individual nodes are accessed uniformly whether they are leaf
nodes or branch (composite) nodes.
using System;
using System.Collections;
namespace DoFactory.GangOfFour.Composite.Structural
{
class MainApp
{
static void Main()
{
// Create a tree structure
Composite root = new Composite("root");
root.Add(new Leaf("Leaf A"));
root.Add(new Leaf("Leaf B"));
root.Add(comp);
root.Add(new Leaf("Leaf C"));
// "Component"
// Constructor
public Component(string name)
{
this.name = name;
}
****** 44
For more informations visit http://www.dofactory.com/Patterns/Patterns.aspx
An Introduction to Design Patterns
// "Composite"
// Constructor
public Composite(string name) : base(name)
{
}
// "Leaf"
****** 45
For more informations visit http://www.dofactory.com/Patterns/Patterns.aspx
An Introduction to Design Patterns
{
Console.WriteLine("Cannot remove from a leaf");
}
Output
-root
---Leaf A
---Leaf B
---Composite X
-----Leaf XA
-----Leaf XB
---Leaf C
This real-world code demonstrates the Composite pattern used in building a graphical
tree structure made up of primitive nodes (lines, circles, etc) and composite nodes
(groups of drawing elements that make up more complex elements).
using System;
using System.Collections;
namespace DoFactory.GangOfFour.Composite.RealWorld
{
class MainApp
{
static void Main()
{
// Create a tree structure
CompositeElement root =
new CompositeElement("Picture");
root.Add(new PrimitiveElement("Red Line"));
root.Add(new PrimitiveElement("Blue Circle"));
root.Add(new PrimitiveElement("Green Box"));
CompositeElement comp =
new CompositeElement("Two Circles");
comp.Add(new PrimitiveElement("Black Circle"));
comp.Add(new PrimitiveElement("White Circle"));
root.Add(comp);
****** 46
For more informations visit http://www.dofactory.com/Patterns/Patterns.aspx
An Introduction to Design Patterns
PrimitiveElement pe =
new PrimitiveElement("Yellow Line");
root.Add(pe);
root.Remove(pe);
// "Component" Treenode
// Constructor
public DrawingElement(string name)
{
this.name = name;
}
// "Leaf"
****** 47
For more informations visit http://www.dofactory.com/Patterns/Patterns.aspx
An Introduction to Design Patterns
// "Composite"
// Constructor
public CompositeElement(string name) : base(name)
{
}
Output
-+ Picture
--- Red Line
--- Blue Circle
--- Green Box
---+ Two Circles
----- Black Circle
----- White Circle
****** 48
For more informations visit http://www.dofactory.com/Patterns/Patterns.aspx
An Introduction to Design Patterns
using System;
namespace DoFactory.GangOfFour.Decorator.Structural
{
****** 49
For more informations visit http://www.dofactory.com/Patterns/Patterns.aspx
An Introduction to Design Patterns
class MainApp
{
static void Main()
{
// Create ConcreteComponent and two Decorators
ConcreteComponent c = new ConcreteComponent();
ConcreteDecoratorA d1 = new ConcreteDecoratorA();
ConcreteDecoratorB d2 = new ConcreteDecoratorB();
// Link decorators
d1.SetComponent(c);
d2.SetComponent(d1);
d2.Operation();
// "Component"
// "ConcreteComponent"
// "Decorator"
****** 50
For more informations visit http://www.dofactory.com/Patterns/Patterns.aspx
An Introduction to Design Patterns
component.Operation();
}
}
}
// "ConcreteDecoratorA"
// "ConcreteDecoratorB"
void AddedBehavior()
{
}
}
}
Output
ConcreteComponent.Operation()
ConcreteDecoratorA.Operation()
ConcreteDecoratorB.Operation()
using System;
using System.Collections;
namespace DoFactory.GangOfFour.Decorator.RealWorld
{
****** 51
For more informations visit http://www.dofactory.com/Patterns/Patterns.aspx
An Introduction to Design Patterns
class MainApp
{
static void Main()
{
// Create book
Book book = new Book ("Worley", "Inside ASP.NET", 10);
book.Display();
// Create video
Video video = new Video ("Spielberg", "Jaws", 23, 92);
video.Display();
borrowvideo.Display();
// "Component"
// Property
public int NumCopies
{
get{ return numCopies; }
set{ numCopies = value; }
}
// "ConcreteComponent"
// Constructor
public Book(string author,string title,int numCopies)
{
this.author = author;
****** 52
For more informations visit http://www.dofactory.com/Patterns/Patterns.aspx
An Introduction to Design Patterns
this.title = title;
this.NumCopies = numCopies;
}
// "ConcreteComponent"
// Constructor
public Video(string director, string title,
int numCopies, int playTime)
{
this.director = director;
this.title = title;
this.NumCopies = numCopies;
this.playTime = playTime;
}
// "Decorator"
// Constructor
public Decorator(LibraryItem libraryItem)
{
this.libraryItem = libraryItem;
}
****** 53
For more informations visit http://www.dofactory.com/Patterns/Patterns.aspx
An Introduction to Design Patterns
{
libraryItem.Display();
}
}
// "ConcreteDecorator"
// Constructor
public Borrowable(LibraryItem libraryItem)
: base(libraryItem)
{
}
Output
Book ------
Author: Worley
Title: Inside ASP.NET
# Copies: 10
Video -----
Director: Spielberg
Title: Jaws
# Copies: 23
Playtime: 92
****** 54
For more informations visit http://www.dofactory.com/Patterns/Patterns.aspx
An Introduction to Design Patterns
Video -----
Director: Spielberg
Title: Jaws
# Copies: 21
Playtime: 92
borrower: Customer #1
borrower: Customer #2
4.5.1 Definition
Provide a unified interface to a set of interfaces in a subsystem. Façade defines a higher-level interface
that makes the subsystem easier to use.
This structural code demonstrates the Facade pattern which provides a simplified and
uniform interface to a large subsystem of classes.
// Facade pattern -- Structural example
****** 55
For more informations visit http://www.dofactory.com/Patterns/Patterns.aspx
An Introduction to Design Patterns
using System;
namespace DoFactory.GangOfFour.Facade.Structural
{
class MainApp
{
public static void Main()
{
Facade facade = new Facade();
facade.MethodA();
facade.MethodB();
// "Subsystem ClassA"
class SubSystemOne
{
public void MethodOne()
{
Console.WriteLine(" SubSystemOne Method");
}
}
// Subsystem ClassB"
class SubSystemTwo
{
public void MethodTwo()
{
Console.WriteLine(" SubSystemTwo Method");
}
}
// Subsystem ClassC"
class SubSystemThree
{
public void MethodThree()
{
Console.WriteLine(" SubSystemThree Method");
}
}
// Subsystem ClassD"
class SubSystemFour
****** 56
For more informations visit http://www.dofactory.com/Patterns/Patterns.aspx
An Introduction to Design Patterns
{
public void MethodFour()
{
Console.WriteLine(" SubSystemFour Method");
}
}
// "Facade"
class Facade
{
SubSystemOne one;
SubSystemTwo two;
SubSystemThree three;
SubSystemFour four;
public Facade()
{
one = new SubSystemOne();
two = new SubSystemTwo();
three = new SubSystemThree();
four = new SubSystemFour();
}
Output
MethodA() ----
SubSystemOne Method
SubSystemTwo Method
SubSystemFour Method
MethodB() ----
SubSystemTwo Method
SubSystemThree Method
****** 57
For more informations visit http://www.dofactory.com/Patterns/Patterns.aspx
An Introduction to Design Patterns
using System;
namespace DoFactory.GangOfFour.Facade.RealWorld
{
// MainApp test application
class MainApp
{
static void Main()
{
// Facade
Mortgage mortgage = new Mortgage();
Console.WriteLine("\n" + customer.Name +
" has been " + (eligable ? "Approved" : "Rejected"));
// "Subsystem ClassA"
class Bank
{
public bool HasSufficientSavings(Customer c, int amount)
{
Console.WriteLine("Check bank for " + c.Name);
return true;
}
}
// "Subsystem ClassB"
class Credit
{
public bool HasGoodCredit(Customer c)
{
Console.WriteLine("Check credit for " + c.Name);
return true;
}
}
// "Subsystem ClassC"
****** 58
For more informations visit http://www.dofactory.com/Patterns/Patterns.aspx
An Introduction to Design Patterns
class Loan
{
public bool HasNoBadLoans(Customer c)
{
Console.WriteLine("Check loans for " + c.Name);
return true;
}
}
class Customer
{
private string name;
// Constructor
public Customer(string name)
{
this.name = name;
}
// Property
public string Name
{
get{ return name; }
}
}
// "Facade"
class Mortgage
{
private Bank bank = new Bank();
private Loan loan = new Loan();
private Credit credit = new Credit();
****** 59
For more informations visit http://www.dofactory.com/Patterns/Patterns.aspx
An Introduction to Design Patterns
return eligible;
}
}
}
Output
Ann McKinsey applies for $125,000.00 loan
****** 60
For more informations visit http://www.dofactory.com/Patterns/Patterns.aspx
An Introduction to Design Patterns
FlyweightFactory (CharacterFactory)
Creates and manages flyweight objects ensures that flyweight are shared properly.
When a client requests a flyweight, the FlyweightFactory objects supplies an existing
instance or creates one, if none exists.
Client (FlyweightApp)
Maintains a reference to flyweight(s). computes or stores the extrinsic state of
flyweight(s).
This structural code demonstrates the Flyweight pattern in which a relatively small
number of objects is shared many times by different clients.
using System;
using System.Collections;
namespace DoFactory.GangOfFour.Flyweight.Structural
{
// MainApp test application
class MainApp
{
static void Main()
{
// Arbitrary extrinsic state
int extrinsicstate = 22;
Flyweight fy = f.GetFlyweight("Y");
fy.Operation(--extrinsicstate);
Flyweight fz = f.GetFlyweight("Z");
fz.Operation(--extrinsicstate);
****** 61
For more informations visit http://www.dofactory.com/Patterns/Patterns.aspx
An Introduction to Design Patterns
UnsharedConcreteFlyweight uf = new
UnsharedConcreteFlyweight();
uf.Operation(--extrinsicstate);
// "FlyweightFactory"
class FlyweightFactory
{
private Hashtable flyweights = new Hashtable();
// Constructor
public FlyweightFactory()
{
flyweights.Add("X", new ConcreteFlyweight());
flyweights.Add("Y", new ConcreteFlyweight());
flyweights.Add("Z", new ConcreteFlyweight());
}
// "Flyweight"
// "ConcreteFlyweight"
// "UnsharedConcreteFlyweight"
****** 62
For more informations visit http://www.dofactory.com/Patterns/Patterns.aspx
An Introduction to Design Patterns
Console.WriteLine("UnsharedConcreteFlyweight: " +
extrinsicstate);
}
}
}
Output
ConcreteFlyweight: 21
ConcreteFlyweight: 20
ConcreteFlyweight: 19
UnsharedConcreteFlyweight: 18
This real-world code demonstrates the Flyweight pattern in which a relatively small
number of Character objects is shared many times by a document that has potentially
many characters.
// Flyweight pattern -- Real World example
using System;
using System.Collections;
namespace DoFactory.GangOfFour.Flyweight.RealWorld
{
class MainApp
{
static void Main()
{
// Build a document with text
string document = "AAZZBBZB";
char[] chars = document.ToCharArray();
// extrinsic state
int pointSize = 10;
// "FlyweightFactory"
****** 63
For more informations visit http://www.dofactory.com/Patterns/Patterns.aspx
An Introduction to Design Patterns
class CharacterFactory
{
private Hashtable characters = new Hashtable();
// "Flyweight"
// "ConcreteFlyweight"
****** 64
For more informations visit http://www.dofactory.com/Patterns/Patterns.aspx
An Introduction to Design Patterns
this.pointSize = pointSize;
Console.WriteLine(this.symbol +
" (pointsize " + this.pointSize + ")");
}
}
// "ConcreteFlyweight"
// ... C, D, E, etc.
// "ConcreteFlyweight"
****** 65
For more informations visit http://www.dofactory.com/Patterns/Patterns.aspx
An Introduction to Design Patterns
Output
A (pointsize 11)
A (pointsize 12)
Z (pointsize 13)
Z (pointsize 14)
B (pointsize 15)
B (pointsize 16)
Z (pointsize 17)
B (pointsize 18)
****** 66
For more informations visit http://www.dofactory.com/Patterns/Patterns.aspx
An Introduction to Design Patterns
virtual proxies may cache additional information about the real subject so that they
can postpone accessing it. For example, the ImageProxy from the Motivation caches the
real images's extent.
protection proxies check that the caller has the access permissions required to
perform a request.
Subject (IMath)
Defines the common interface for RealSubject and Proxy so that a Proxy can be used
anywhere a RealSubject is expected.
RealSubject (Math)
Defines the real object that the proxy represents.
This structural code demonstrates the Proxy pattern which provides a representative
object (proxy) that controls access to another similar object.
using System;
namespace DoFactory.GangOfFour.Proxy.Structural
{
class MainApp
{
static void Main()
{
// Create proxy and request a service
Proxy proxy = new Proxy();
proxy.Request();
// "Subject"
// "RealSubject"
****** 67
For more informations visit http://www.dofactory.com/Patterns/Patterns.aspx
An Introduction to Design Patterns
{
Console.WriteLine("Called RealSubject.Request()");
}
}
// "Proxy"
realSubject.Request();
}
}
}
Output
Called RealSubject.Request()
This real-world code demonstrates the Proxy pattern for a Math object represented by a
MathProxy object.
// Proxy pattern -- Real World example
using System;
namespace DoFactory.GangOfFour.Proxy.RealWorld
{
class MainApp
{
static void Main()
{
// Create math proxy
MathProxy p = new MathProxy();
// Do the math
Console.WriteLine("4 + 2 = " + p.Add(4, 2));
Console.WriteLine("4 - 2 = " + p.Sub(4, 2));
Console.WriteLine("4 * 2 = " + p.Mul(4, 2));
Console.WriteLine("4 / 2 = " + p.Div(4, 2));
****** 68
For more informations visit http://www.dofactory.com/Patterns/Patterns.aspx
An Introduction to Design Patterns
Console.Read();
}
}
// "Subject"
// "RealSubject"
// "Proxy Object"
public MathProxy()
{
math = new Math();
}
****** 69
For more informations visit http://www.dofactory.com/Patterns/Patterns.aspx
An Introduction to Design Patterns
Output
4+2=6
4-2=2
4*2=8
4/2=2
This structural code demonstrates the Chain of Responsibility pattern in which several
linked objects (the Chain) are offered the opportunity to respond to a request or hand it
off to the object next in line.
// Chain of Responsibility pattern -- Structural example
using System;
namespace DoFactory.GangOfFour.Chain.Structural
****** 70
For more informations visit http://www.dofactory.com/Patterns/Patterns.aspx
An Introduction to Design Patterns
{
// MainApp test application
class MainApp
{
static void Main()
{
// Setup Chain of Responsibility
Handler h1 = new ConcreteHandler1();
Handler h2 = new ConcreteHandler2();
Handler h3 = new ConcreteHandler3();
h1.SetSuccessor(h2);
h2.SetSuccessor(h3);
// "Handler"
// "ConcreteHandler1"
****** 71
For more informations visit http://www.dofactory.com/Patterns/Patterns.aspx
An Introduction to Design Patterns
successor.HandleRequest(request);
}
}
}
// "ConcreteHandler2"
// "ConcreteHandler3"
Output
ConcreteHandler1 handled request 2
ConcreteHandler1 handled request 5
ConcreteHandler2 handled request 14
ConcreteHandler3 handled request 22
ConcreteHandler2 handled request 18
ConcreteHandler1 handled request 3
ConcreteHandler3 handled request 27
ConcreteHandler3 handled request 20
****** 72
For more informations visit http://www.dofactory.com/Patterns/Patterns.aspx
An Introduction to Design Patterns
This real-world code demonstrates the Chain of Responsibility pattern in which several
linked managers and executives can respond to a purchase request or hand it off to a
superior. Each position has can have its own set of rules which orders they can
approve.
// Chain of Responsibility pattern -- Real World example
using System;
namespace DoFactory.GangOfFour.Chain.RealWorld
{
class MainApp
{
static void Main()
{
// Setup Chain of Responsibility
Director Larry = new Director();
VicePresident Sam = new VicePresident();
President Tammy = new President();
Larry.SetSuccessor(Sam);
Sam.SetSuccessor(Tammy);
// "Handler"
// "ConcreteHandler"
****** 73
For more informations visit http://www.dofactory.com/Patterns/Patterns.aspx
An Introduction to Design Patterns
// "ConcreteHandler"
// "ConcreteHandler"
****** 74
For more informations visit http://www.dofactory.com/Patterns/Patterns.aspx
An Introduction to Design Patterns
// Request details
class Purchase
{
private int number;
private double amount;
private string purpose;
// Constructor
public Purchase(int number, double amount, string purpose)
{
this.number = number;
this.amount = amount;
this.purpose = purpose;
}
// Properties
public double Amount
{
get{ return amount; }
set{ amount = value; }
}
Output
Director Larry approved request# 2034
President Tammy approved request# 2035
Request# 2036 requires an executive meeting!
****** 75
For more informations visit http://www.dofactory.com/Patterns/Patterns.aspx
An Introduction to Design Patterns
This structural code demonstrates the Command pattern which stores requests as
objects allowing clients to execute or playback the requests.
// Command pattern -- Structural example
using System;
namespace DoFactory.GangOfFour.Command.Structural
{
****** 76
For more informations visit http://www.dofactory.com/Patterns/Patterns.aspx
An Introduction to Design Patterns
class MainApp
{
static void Main()
{
// Create receiver, command, and invoker
Receiver receiver = new Receiver();
Command command = new ConcreteCommand(receiver);
Invoker invoker = new Invoker();
// "Command"
// Constructor
public Command(Receiver receiver)
{
this.receiver = receiver;
}
// "ConcreteCommand"
// "Receiver"
class Receiver
{
****** 77
For more informations visit http://www.dofactory.com/Patterns/Patterns.aspx
An Introduction to Design Patterns
// "Invoker"
class Invoker
{
private Command command;
Output
Called Receiver.Action()
This real-world code demonstrates the Command pattern used in a simple calculator
with unlimited number of undo's and redo's. Note that in C# the word 'operator' is a
keyword. Prefixing it with '@' allows using it as an identifier.
// Command pattern -- Real World example
using System;
using System.Collections;
namespace DoFactory.GangOfFour.Command.RealWorld
{
class MainApp
{
static void Main()
{
// Create user and let her compute
User user = new User();
user.Compute('+', 100);
user.Compute('-', 50);
user.Compute('*', 10);
user.Compute('/', 2);
// Undo 4 commands
user.Undo(4);
****** 78
For more informations visit http://www.dofactory.com/Patterns/Patterns.aspx
An Introduction to Design Patterns
// Redo 3 commands
user.Redo(3);
// "Command"
// "ConcreteCommand"
// Constructor
public CalculatorCommand(Calculator calculator,
char @operator, int operand)
{
this.calculator = calculator;
this.@operator = @operator;
this.operand = operand;
}
****** 79
For more informations visit http://www.dofactory.com/Patterns/Patterns.aspx
An Introduction to Design Patterns
// "Receiver"
class Calculator
{
private int curr = 0;
// "Invoker"
class User
{
// Initializers
private Calculator calculator = new Calculator();
private ArrayList commands = new ArrayList();
****** 80
For more informations visit http://www.dofactory.com/Patterns/Patterns.aspx
An Introduction to Design Patterns
{
Command command = commands[current++] as Command;
command.Execute();
}
}
}
Output
Current value = 100 (following + 100)
Current value = 50 (following - 50)
Current value = 500 (following * 10)
Current value = 250 (following / 2)
****** 81
For more informations visit http://www.dofactory.com/Patterns/Patterns.aspx
An Introduction to Design Patterns
This structural code demonstrates the Interpreter patterns, which using a defined
grammer, provides the interpreter that processes parsed statements.
// Interpreter pattern -- Structural example
using System;
using System.Collections;
****** 82
For more informations visit http://www.dofactory.com/Patterns/Patterns.aspx
An Introduction to Design Patterns
namespace DoFactory.GangOfFour.Interpreter.Structural
{
class MainApp
{
static void Main()
{
Context context = new Context();
// Usually a tree
ArrayList list = new ArrayList();
// Interpret
foreach (AbstractExpression exp in list)
{
exp.Interpret(context);
}
// "Context"
class Context
{
}
// "AbstractExpression"
// "TerminalExpression"
****** 83
For more informations visit http://www.dofactory.com/Patterns/Patterns.aspx
An Introduction to Design Patterns
// "NonterminalExpression"
Output
Called Terminal.Interpret()
Called Nonterminal.Interpret()
Called Terminal.Interpret()
Called Terminal.Interpret()
This real-world code demonstrates the Interpreter pattern which is used to convert a
Roman numeral to a decimal.
// Interpreter pattern -- Real World example
using System;
using System.Collections;
namespace DoFactory.GangOfFour.Interpreter.RealWorld
{
class MainApp
{
static void Main()
{
string roman = "MCMXXVIII";
Context context = new Context(roman);
// Interpret
foreach (Expression exp in tree)
{
exp.Interpret(context);
}
Console.WriteLine("{0} = {1}",
roman, context.Output);
****** 84
For more informations visit http://www.dofactory.com/Patterns/Patterns.aspx
An Introduction to Design Patterns
Console.Read();
}
}
// "Context"
class Context
{
private string input;
private int output;
// Constructor
public Context(string input)
{
this.input = input;
}
// Properties
public string Input
{
get{ return input; }
set{ input = value; }
}
// "AbstractExpression"
if (context.Input.StartsWith(Nine()))
{
context.Output += (9 * Multiplier());
context.Input = context.Input.Substring(2);
}
else if (context.Input.StartsWith(Four()))
{
context.Output += (4 * Multiplier());
context.Input = context.Input.Substring(2);
}
else if (context.Input.StartsWith(Five()))
{
context.Output += (5 * Multiplier());
context.Input = context.Input.Substring(1);
****** 85
For more informations visit http://www.dofactory.com/Patterns/Patterns.aspx
An Introduction to Design Patterns
while (context.Input.StartsWith(One()))
{
context.Output += (1 * Multiplier());
context.Input = context.Input.Substring(1);
}
}
// One checks for I, II, III, IV, V, VI, VI, VII, VIII, IX
// "TerminalExpression"
****** 86
For more informations visit http://www.dofactory.com/Patterns/Patterns.aspx
An Introduction to Design Patterns
Output
MCMXXVIII = 1928
****** 87
For more informations visit http://www.dofactory.com/Patterns/Patterns.aspx
An Introduction to Design Patterns
using System;
using System.Collections;
namespace DoFactory.GangOfFour.Iterator.Structural
{
class MainApp
{
static void Main()
{
ConcreteAggregate a = new ConcreteAggregate();
a[0] = "Item A";
a[1] = "Item B";
a[2] = "Item C";
a[3] = "Item D";
// "Aggregate"
// "ConcreteAggregate"
****** 88
For more informations visit http://www.dofactory.com/Patterns/Patterns.aspx
An Introduction to Design Patterns
{
private ArrayList items = new ArrayList();
// Property
public int Count
{
get{ return items.Count; }
}
// Indexer
public object this[int index]
{
get{ return items[index]; }
set{ items.Insert(index, value); }
}
}
// "Iterator"
// "ConcreteIterator"
// Constructor
public ConcreteIterator(ConcreteAggregate aggregate)
{
this.aggregate = aggregate;
}
****** 89
For more informations visit http://www.dofactory.com/Patterns/Patterns.aspx
An Introduction to Design Patterns
{
ret = aggregate[++current];
}
return ret;
}
Output
Iterating over collection:
Item A
Item B
Item C
Item D
This real-world code demonstrates the Iterator pattern which is used to iterate over a
collection of items and skip a specific number of items each iteration.
// Iterator pattern -- Real World example
using System;
using System.Collections;
namespace DoFactory.GangOfFour.Iterator.RealWorld
{
class MainApp
{
static void Main()
{
// Build a collection
Collection collection = new Collection();
collection[0] = new Item("Item 0");
collection[1] = new Item("Item 1");
collection[2] = new Item("Item 2");
collection[3] = new Item("Item 3");
collection[4] = new Item("Item 4");
collection[5] = new Item("Item 5");
collection[6] = new Item("Item 6");
collection[7] = new Item("Item 7");
collection[8] = new Item("Item 8");
****** 90
For more informations visit http://www.dofactory.com/Patterns/Patterns.aspx
An Introduction to Design Patterns
// Create iterator
Iterator iterator = new Iterator(collection);
class Item
{
string name;
// Constructor
public Item(string name)
{
this.name = name;
}
// Property
public string Name
{
get{ return name; }
}
}
// "Aggregate"
interface IAbstractCollection
{
Iterator CreateIterator();
}
// "ConcreteAggregate"
****** 91
For more informations visit http://www.dofactory.com/Patterns/Patterns.aspx
An Introduction to Design Patterns
// Property
public int Count
{
get{ return items.Count; }
}
// Indexer
public object this[int index]
{
get{ return items[index]; }
set{ items.Add(value); }
}
}
// "Iterator"
interface IAbstractIterator
{
Item First();
Item Next();
bool IsDone{ get; }
Item CurrentItem{ get; }
}
// "ConcreteIterator"
// Constructor
public Iterator(Collection collection)
{
this.collection = collection;
}
// Properties
****** 92
For more informations visit http://www.dofactory.com/Patterns/Patterns.aspx
An Introduction to Design Patterns
Output
Iterating over collection:
Item 0
Item 2
Item 4
Item 6
Item 8
****** 93
For more informations visit http://www.dofactory.com/Patterns/Patterns.aspx
An Introduction to Design Patterns
This structural code demonstrates the Mediator pattern facilitating loosely coupled
communication between different objects and object types. The mediator is a central
hub through which all interaction must take place.
// Mediator pattern -- Structural example
using System;
using System.Collections;
namespace DoFactory.GangOfFour.Mediator.Structural
{
class MainApp
{
static void Main()
{
****** 94
For more informations visit http://www.dofactory.com/Patterns/Patterns.aspx
An Introduction to Design Patterns
m.Colleague1 = c1;
m.Colleague2 = c2;
// "Mediator"
// "ConcreteMediator"
****** 95
For more informations visit http://www.dofactory.com/Patterns/Patterns.aspx
An Introduction to Design Patterns
// "Colleague"
// Constructor
public Colleague(Mediator mediator)
{
this.mediator = mediator;
}
}
// "ConcreteColleague1"
// "ConcreteColleague2"
****** 96
For more informations visit http://www.dofactory.com/Patterns/Patterns.aspx
An Introduction to Design Patterns
+ message);
}
}
}
Output
Colleague2 gets message: How are you?
Colleague1 gets message: Fine, thanks
This real-world code demonstrates the Mediator pattern facilitating loosely coupled
communication between different Participants registering with a Chatroom. The
Chatroom is the central hub through which all communication takes place. At this
point only one-to-one communication is implemented in the Chatroom, but would be
trivial to change to one-to-many.
// Mediator pattern -- Real World example
using System;
using System.Collections;
namespace DoFactory.GangOfFour.Mediator.RealWorld
{
class MainApp
{
static void Main()
{
// Create chatroom
Chatroom chatroom = new Chatroom();
chatroom.Register(George);
chatroom.Register(Paul);
chatroom.Register(Ringo);
chatroom.Register(John);
chatroom.Register(Yoko);
// Chatting participants
Yoko.Send ("John", "Hi John!");
Paul.Send ("Ringo", "All you need is love");
Ringo.Send("George", "My sweet Lord");
Paul.Send ("John", "Can't buy me love");
John.Send ("Yoko", "My sweet love") ;
****** 97
For more informations visit http://www.dofactory.com/Patterns/Patterns.aspx
An Introduction to Design Patterns
Console.Read();
}
}
// "Mediator"
// "ConcreteMediator"
participant.Chatroom = this;
}
// "AbstractColleague"
class Participant
{
private Chatroom chatroom;
private string name;
// Constructor
public Participant(string name)
{
this.name = name;
}
// Properties
****** 98
For more informations visit http://www.dofactory.com/Patterns/Patterns.aspx
An Introduction to Design Patterns
//" ConcreteColleague1"
//" ConcreteColleague2"
****** 99
For more informations visit http://www.dofactory.com/Patterns/Patterns.aspx
An Introduction to Design Patterns
}
}
Output
To a Beatle: Yoko to John: 'Hi John!'
To a Beatle: Paul to Ringo: 'All you need is love'
To a Beatle: Ringo to George: 'My sweet Lord'
To a Beatle: Paul to John: 'Can't buy me love'
To a non-Beatle: John to Yoko: 'My sweet love'
****** 100
For more informations visit http://www.dofactory.com/Patterns/Patterns.aspx
An Introduction to Design Patterns
This structural code demonstrates the Memento pattern which temporary saves and
restores another object's internal state.
// Memento pattern -- Structural example
using System;
namespace DoFactory.GangOfFour.Memento.Structural
{
class MainApp
{
static void Main()
{
Originator o = new Originator();
o.State = "On";
// "Originator"
class Originator
{
private string state;
// Property
public string State
{
get{ return state; }
set
{
state = value;
Console.WriteLine("State = " + state);
}
}
****** 101
For more informations visit http://www.dofactory.com/Patterns/Patterns.aspx
An Introduction to Design Patterns
// "Memento"
class Memento
{
private string state;
// Constructor
public Memento(string state)
{
this.state = state;
}
// Property
public string State
{
get{ return state; }
}
}
// "Caretaker"
class Caretaker
{
private Memento memento;
// Property
public Memento Memento
{
set{ memento = value; }
get{ return memento; }
}
}
}
Output
State = On
State = Off
Restoring state:
State = On
This real-world code demonstrates the Memento pattern which temporarily saves and
then restores the SalesProspect's internal state.
// Memento pattern -- Real World example
****** 102
For more informations visit http://www.dofactory.com/Patterns/Patterns.aspx
An Introduction to Design Patterns
using System;
namespace DoFactory.GangOfFour.Memento.RealWorld
{
class MainApp
{
static void Main()
{
SalesProspect s = new SalesProspect();
s.Name = "Noel van Halen";
s.Phone = "(412) 256-0990";
s.Budget = 25000.0;
// "Originator"
class SalesProspect
{
private string name;
private string phone;
private double budget;
// Properties
public string Name
{
get{ return name; }
set
{
name = value;
Console.WriteLine("Name: " + name);
}
}
****** 103
For more informations visit http://www.dofactory.com/Patterns/Patterns.aspx
An Introduction to Design Patterns
{
get{ return phone; }
set
{
phone = value;
Console.WriteLine("Phone: " + phone);
}
}
// "Memento"
class Memento
{
private string name;
private string phone;
private double budget;
// Constructor
public Memento(string name, string phone, double budget)
{
this.name = name;
this.phone = phone;
this.budget = budget;
}
// Properties
public string Name
{
get{ return name; }
****** 104
For more informations visit http://www.dofactory.com/Patterns/Patterns.aspx
An Introduction to Design Patterns
// "Caretaker"
class ProspectMemory
{
private Memento memento;
// Property
public Memento Memento
{
set{ memento = value; }
get{ return memento; }
}
}
}
Output
Name: Noel van Halen
Phone: (412) 256-0990
Budget: 25000
Saving state --
Restoring state --
****** 105
For more informations visit http://www.dofactory.com/Patterns/Patterns.aspx
An Introduction to Design Patterns
This structural code demonstrates the Observer pattern in which registered objects are
notified of and updated with a state change.
// Observer pattern -- Structural example
using System;
using System.Collections;
****** 106
For more informations visit http://www.dofactory.com/Patterns/Patterns.aspx
An Introduction to Design Patterns
namespace DoFactory.GangOfFour.Observer.Structural
{
class MainApp
{
static void Main()
{
// Configure Observer pattern
ConcreteSubject s = new ConcreteSubject();
s.Attach(new ConcreteObserver(s,"X"));
s.Attach(new ConcreteObserver(s,"Y"));
s.Attach(new ConcreteObserver(s,"Z"));
// "Subject"
// "ConcreteSubject"
****** 107
For more informations visit http://www.dofactory.com/Patterns/Patterns.aspx
An Introduction to Design Patterns
{
private string subjectState;
// Property
public string SubjectState
{
get{ return subjectState; }
set{ subjectState = value; }
}
}
// "Observer"
// "ConcreteObserver"
// Constructor
public ConcreteObserver(
ConcreteSubject subject, string name)
{
this.subject = subject;
this.name = name;
}
// Property
public ConcreteSubject Subject
{
get { return subject; }
set { subject = value; }
}
}
}
Output
Observer X's new state is ABC
Observer Y's new state is ABC
Observer Z's new state is ABC
****** 108
For more informations visit http://www.dofactory.com/Patterns/Patterns.aspx
An Introduction to Design Patterns
This real-world code demonstrates the Observer pattern in which registered investors
are notified every time a stock changes value.
// Observer pattern -- Real World example
using System;
using System.Collections;
namespace DoFactory.GangOfFour.Observer.RealWorld
{
class MainApp
{
static void Main()
{
// Create investors
Investor s = new Investor("Sorros");
Investor b = new Investor("Berkshire");
// "Subject"
// Constructor
public Stock(string symbol, double price)
{
this.symbol = symbol;
this.price = price;
}
****** 109
For more informations visit http://www.dofactory.com/Patterns/Patterns.aspx
An Introduction to Design Patterns
// Properties
public double Price
{
get{ return price; }
set
{
price = value;
Notify();
}
}
// "ConcreteSubject"
// "Observer"
interface IInvestor
{
void Update(Stock stock);
}
// "ConcreteObserver"
****** 110
For more informations visit http://www.dofactory.com/Patterns/Patterns.aspx
An Introduction to Design Patterns
// Constructor
public Investor(string name)
{
this.name = name;
}
// Property
public Stock Stock
{
get{ return stock; }
set{ stock = value; }
}
}
}
Output
Notified Sorros of IBM's change to $120.10
Notified Berkshire of IBM's change to $120.10
****** 111
For more informations visit http://www.dofactory.com/Patterns/Patterns.aspx
An Introduction to Design Patterns
using System;
namespace DoFactory.GangOfFour.State.Structural
{
class MainApp
{
static void Main()
{
// Setup context in a state
Context c = new Context(new ConcreteStateA());
****** 112
For more informations visit http://www.dofactory.com/Patterns/Patterns.aspx
An Introduction to Design Patterns
c.Request();
c.Request();
c.Request();
// "State"
// "ConcreteStateA"
// "ConcreteStateB"
// "Context"
class Context
{
private State state;
// Constructor
public Context(State state)
{
this.State = state;
}
// Property
public State State
{
get{ return state; }
set
{
****** 113
For more informations visit http://www.dofactory.com/Patterns/Patterns.aspx
An Introduction to Design Patterns
state = value;
Console.WriteLine("State: " +
state.GetType().Name);
}
}
Output
State: ConcreteStateA
State: ConcreteStateB
State: ConcreteStateA
State: ConcreteStateB
State: ConcreteStateA
This real-world code demonstrates the State pattern which allows an Account to behave
differently depending on its balance. The difference in behavior is delegated to State
objects called RedState, SilverState and GoldState. These states represent overdrawn
accounts, starter accounts, and accounts in good standing.
// State pattern -- Real World example
using System;
namespace DoFactory.GangOfFour.State.RealWorld
{
class MainApp
{
static void Main()
{
// Open a new account
Account account = new Account("Jim Johnson");
****** 114
For more informations visit http://www.dofactory.com/Patterns/Patterns.aspx
An Introduction to Design Patterns
// "State"
// Properties
public Account Account
{
get{ return account; }
set{ account = value; }
}
// "ConcreteState"
// Account is overdrawn
// Constructor
public RedState(State state)
{
this.balance = state.Balance;
this.account = state.Account;
Initialize();
}
****** 115
For more informations visit http://www.dofactory.com/Patterns/Patterns.aspx
An Introduction to Design Patterns
// "ConcreteState"
****** 116
For more informations visit http://www.dofactory.com/Patterns/Patterns.aspx
An Introduction to Design Patterns
// "ConcreteState"
****** 117
For more informations visit http://www.dofactory.com/Patterns/Patterns.aspx
An Introduction to Design Patterns
lowerLimit = 1000.0;
upperLimit = 10000000.0;
}
// "Context"
class Account
{
private State state;
private string owner;
// Constructor
public Account(string owner)
{
// New accounts are 'Silver' by default
this.owner = owner;
state = new SilverState(0.0, this);
}
// Properties
public double Balance
{
get{ return state.Balance; }
****** 118
For more informations visit http://www.dofactory.com/Patterns/Patterns.aspx
An Introduction to Design Patterns
Output
Deposited $500.00 ---
Balance = $500.00
Status = SilverState
****** 119
For more informations visit http://www.dofactory.com/Patterns/Patterns.aspx
An Introduction to Design Patterns
using System;
****** 120
For more informations visit http://www.dofactory.com/Patterns/Patterns.aspx
An Introduction to Design Patterns
namespace DoFactory.GangOfFour.Strategy.Structural
{
class MainApp
{
static void Main()
{
Context context;
// "Strategy"
// "ConcreteStrategyA"
// "ConcreteStrategyB"
****** 121
For more informations visit http://www.dofactory.com/Patterns/Patterns.aspx
An Introduction to Design Patterns
// "ConcreteStrategyC"
// "Context"
class Context
{
Strategy strategy;
// Constructor
public Context(Strategy strategy)
{
this.strategy = strategy;
}
Output
Called ConcreteStrategyA.AlgorithmInterface()
Called ConcreteStrategyB.AlgorithmInterface()
Called ConcreteStrategyC.AlgorithmInterface()
This real-world code demonstrates the Strategy pattern which encapsulates sorting
algorithms in the form of sorting objects. This allows clients to dynamically change
sorting strategies including Quicksort, Shellsort, and Mergesort.
// Strategy pattern -- Real World example
using System;
using System.Collections;
namespace DoFactory.GangOfFour.Strategy.RealWorld
{
class MainApp
{
static void Main()
{
****** 122
For more informations visit http://www.dofactory.com/Patterns/Patterns.aspx
An Introduction to Design Patterns
studentRecords.Add("Samual");
studentRecords.Add("Jimmy");
studentRecords.Add("Sandra");
studentRecords.Add("Vivek");
studentRecords.Add("Anna");
studentRecords.SetSortStrategy(new QuickSort());
studentRecords.Sort();
studentRecords.SetSortStrategy(new ShellSort());
studentRecords.Sort();
studentRecords.SetSortStrategy(new MergeSort());
studentRecords.Sort();
// "Strategy"
// "ConcreteStrategy"
// "ConcreteStrategy"
// "ConcreteStrategy"
****** 123
For more informations visit http://www.dofactory.com/Patterns/Patterns.aspx
An Introduction to Design Patterns
// "Context"
class SortedList
{
private ArrayList list = new ArrayList();
private SortStrategy sortstrategy;
// Display results
foreach (string name in list)
{
Console.WriteLine(" " + name);
}
Console.WriteLine();
}
}
}
Output
QuickSorted list
Anna
Jimmy
Samual
Sandra
Vivek
ShellSorted list
Anna
Jimmy
Samual
Sandra
Vivek
****** 124
For more informations visit http://www.dofactory.com/Patterns/Patterns.aspx
An Introduction to Design Patterns
MergeSorted list
Anna
Jimmy
Samual
Sandra
Vivek
using System;
****** 125
For more informations visit http://www.dofactory.com/Patterns/Patterns.aspx
An Introduction to Design Patterns
namespace DoFactory.GangOfFour.Template.Structural
{
class MainApp
{
static void Main()
{
AbstractClass c;
c = new ConcreteClassA();
c.TemplateMethod();
c = new ConcreteClassB();
c.TemplateMethod();
// "AbstractClass"
// "ConcreteClass"
****** 126
For more informations visit http://www.dofactory.com/Patterns/Patterns.aspx
An Introduction to Design Patterns
{
public override void PrimitiveOperation1()
{
Console.WriteLine("ConcreteClassB.PrimitiveOperation1()");
}
public override void PrimitiveOperation2()
{
Console.WriteLine("ConcreteClassB.PrimitiveOperation2()");
}
}
}
Output
ConcreteClassA.PrimitiveOperation1()
ConcreteClassA.PrimitiveOperation2()
This real-world code demonstrates a Template method named Run() which provides a
skeleton calling sequence of methods. Implementation of these steps are deferred to the
CustomerDataObject subclass which implements the Connect, Select, Process, and
Disconnect methods.
// Template pattern -- Real World example
using System;
using System.Data;
using System.Data.OleDb;
namespace DoFactory.GangOfFour.Template.RealWorld
{
class MainApp
{
static void Main()
{
DataAccessObject dao;
// "AbstractClass"
****** 127
For more informations visit http://www.dofactory.com/Patterns/Patterns.aspx
An Introduction to Design Patterns
// "ConcreteClass"
****** 128
For more informations visit http://www.dofactory.com/Patterns/Patterns.aspx
An Introduction to Design Patterns
Output
Categories ----
Beverages
Condiments
Confections
Dairy Products
Grains/Cereals
Meat/Poultry
Produce
Seafood
Products ----
Chai
Chang
Aniseed Syrup
Chef Anton's Cajun Seasoning
Chef Anton's Gumbo Mix
Grandma's Boysenberry Spread
Uncle Bob's Organic Dried Pears
Northwoods Cranberry Sauce
Mishi Kobe Niku
****** 129
For more informations visit http://www.dofactory.com/Patterns/Patterns.aspx
An Introduction to Design Patterns
****** 130
For more informations visit http://www.dofactory.com/Patterns/Patterns.aspx
An Introduction to Design Patterns
ConcreteVisitor provides the context for the algorithm and stores its local state. This
state often accumulates results during the traversal of the structure.
Element (Element)
Defines an Accept operation that takes a visitor as an argument.
ConcreteElement (Employee)
Implements an Accept operation that takes a visitor as an argument
ObjectStructure (Employees)
Can enumerate its elements
May provide a high-level interface to allow the visitor to visit its elements
May either be a Composite (pattern) or a collection such as a list or a set
namespace DoFactory.GangOfFour.Visitor.Structural
{
class MainApp
{
static void Main()
{
// Setup structure
ObjectStructure o = new ObjectStructure();
o.Attach(new ConcreteElementA());
o.Attach(new ConcreteElementB());
// "Visitor"
****** 131
For more informations visit http://www.dofactory.com/Patterns/Patterns.aspx
An Introduction to Design Patterns
ConcreteElementB concreteElementB);
}
// "ConcreteVisitor1"
// "ConcreteVisitor2"
// "Element"
// "ConcreteElementA"
****** 132
For more informations visit http://www.dofactory.com/Patterns/Patterns.aspx
An Introduction to Design Patterns
visitor.VisitConcreteElementA(this);
}
// "ConcreteElementB"
// "ObjectStructure"
class ObjectStructure
{
private ArrayList elements = new ArrayList();
Output
ConcreteElementA visited by ConcreteVisitor1
ConcreteElementB visited by ConcreteVisitor1
ConcreteElementA visited by ConcreteVisitor2
ConcreteElementB visited by ConcreteVisitor2
****** 133
For more informations visit http://www.dofactory.com/Patterns/Patterns.aspx
An Introduction to Design Patterns
This real-world code demonstrates the Visitor pattern in which two objects traverse a
list of Employees and performs the same operation on each Employee. The two visitor
objects define different operations -- one adjusts vacation days and the other income.
// Visitor pattern -- Real World example
using System;
using System.Collections;
namespace DoFactory.GangOfFour.Visitor.RealWorld
{
class MainApp
{
static void Main()
{
// Setup employee collection
Employees e = new Employees();
e.Attach(new Clerk());
e.Attach(new Director());
e.Attach(new President());
// "Visitor"
interface IVisitor
{
void Visit(Element element);
}
// "ConcreteVisitor1"
****** 134
For more informations visit http://www.dofactory.com/Patterns/Patterns.aspx
An Introduction to Design Patterns
// "ConcreteVisitor2"
// "Element"
// "ConcreteElement"
****** 135
For more informations visit http://www.dofactory.com/Patterns/Patterns.aspx
An Introduction to Design Patterns
// Constructor
public Employee(string name, double income,
int vacationDays)
{
this.name = name;
this.income = income;
this.vacationDays = vacationDays;
}
// Properties
public string Name
{
get{ return name; }
set{ name = value; }
}
// "ObjectStructure"
class Employees
{
private ArrayList employees = new ArrayList();
****** 136
For more informations visit http://www.dofactory.com/Patterns/Patterns.aspx
An Introduction to Design Patterns
{
e.Accept(visitor);
}
Console.WriteLine();
}
}
}
Output
Clerk Hank's new income: $27,500.00
Director Elly's new income: $38,500.00
President Dick's new income: $49,500.00
: END :
****** 137
For more informations visit http://www.dofactory.com/Patterns/Patterns.aspx