Design patterns
History
The concept of a "pattern" was first expressed in Christopher
Alexander's work A Pattern Language in 1977 (2543 patterns)
In 1990 a group called the Gang of Four or "GoF" (Gamma,
Helm, Johnson, Vlissides) compile a catalog of design
patterns
Design Pattern: A solution to a common software
problem in a context
Example: Iterator pattern
The Iterator pattern defines an interface that declares
methods for sequentially accessing the objects in a collection.
1
More about patterns
A pattern describes a recurring software structure
Is abstract from concrete design elements such as problem domain,
programming language
Identifies classes that play a role in the solution to a problem, describes
their collaborations and responsibilities
Lists implementation trade-offs
Patterns are not code or designs; must be instantiated/applied
The software engineer is required to:
Evaluate trade-offs and impact of using a pattern in the system at hand
Make design and implementation decision how best to apply the
pattern, perhaps modify it slightly
Implement the pattern in code and combine it with other patterns
2
More about patterns
A pattern describes a recurring software structure
Is abstract from concrete design elements such as problem domain,
programming language
Identifies classes that play a role in the solution to a problem,
describes their collaborations and responsibilities
The software engineer is required to:
Evaluate trade-offs and impact of using a pattern in the system at
hand
Make design and implementation decision how best to apply the
pattern, perhaps modify it slightly
Implement the pattern in code and combine it with other patterns
3
Types of Pattern
There are 3 types of pattern …
Creational: address problems of creating an object in
a flexible way. Separate creation, from operation/use.
Structural: address problems of using O-O
constructs like inheritance to organize classes and
objects
Behavioral: address problems of assigning
responsibilities to classes. Suggest both static
relationships and patterns of communication
(use cases)
Gang of Four (GoF) patterns
Creational Patterns
(concerned with abstracting the object-
instantiation process)
Factory Method
Abstract Factory
Singleton
Builder
Prototype
5
Factory pattern
Factory: a class whose sole job is to easily create
and return instances of other classes
A creational pattern; makes it easier to construct
complex objects
Instead of calling a constructor, use a static
method in a "factory" class to set up the object
Saves lines and complexity to quickly construct /
initialize objects
Examples in Java: borders (BorderFactory),
network connections (SocketFactory)
6
Using existing factories in Java
setting borders on buttons and panels
use built-in BorderFactory class
myButton.setBorder(
BorderFactory.createRaisedBevelBorder());
7
The Factory Method
Motivation: Class / Type separation
Design Pattern
Abstract class serves as type definition and concrete class provides
implementation
In a language which distinguishes between class and type, there must be a
mechanism for creation of an object which would reveal its type, but not
its class.
Unfortunately, in Java, the best known language in which such a
separation exists, there is no such mechanism. Abstract Methods deal
exactly with this problem. The Abstract Factory Generalizes.
Pattern Intent: Define an interface for creating an object, but let subclasses
decide which class to instantiate.
Lets a class defer instantiation to subclasses
Factory Method Motivation
Document* Application*
Open() docs CreateDocument() Document* doc = CreateDocument();
Close() NewDocument() docs.Add(doc);
Save() OpenDocument() doc ->Open();
Revert()
MyDocument MyApplication
CreateDocument() return new MyDocument
Factory Method pattern
Motivation
Document
docs Application
Open() Document* doc = CreateDocument();
Save() CreateDocument() docs.Add(doc);
Close() NewDocument() doc->Open();
Revert() OpenDocument()
MyApplication
MyDocument CreateDocument() return new MyDocument
creates
Factory Method pattern
Motivation (cont.)
Application class is responsible for creation (and
management) of Documents
Problem:
Application class knows: WHEN a new document should be
created
Application class doesn’t know: WHAT KIND of document to
create
Solution:
Application subclasses redefine abstract CreateDocument()
method to return an appropriate Document subclass instance
Factory Method Structure Creator*
Product* FactoryMethod() ...
AnOperation() product = FactoryMethod()
...
ConcreteCreator
ConcreteProduct*
FactoryMethod() return new ConcreteProduct
Define an interface for creating an object, but let subclasses decide which
class to instantiate. Factory Method lets a class defer instantiation to
subclasses.
Factory Method Consequences
Figure* Client Manipulator*
createManipulator() DownClick()
... Drag()
Upclick()
LineFigure TextFigure LineManipulator TextManipulator
createManipulator() createManipulator() DownClick() DownClick()
... ... Drag() Drag()
Upclick() Upclick()
Connecting parallel hierarchies
Manipulator
Figure Client DownClick()
CreateManipulator() Drag()
LineManipulator TextManipulator
LineFigure TextFigure
DownClick() DownClick()
CreateManipulator() CreateManipulator()
Drag() Drag()
creates
creates
Localizes knowledge of which classes belongs together
Factory Method pattern
Structure
Creator ...
FactoryMethod() product= FactoryMethod()
Product
AnOperation() ...
ConcreteProduct ConcreteCreator
return new ConcreteProduct
FactoryMethod()
creates
Factory Method pattern
Applicability
Use the Factory Method pattern when
a class can’t anticipate the class of objects it must create
a class wants its subclasses to specify the object it creates
classes delegate responsibility to one of several helper
subclasses, and you want to localize the knowledge of which
helper subclass is the delegate
Factory Method pattern
Participants
Product (Document)
defines the interface of objects the factory method creates
ConcreteProduct (MyDocument)
implements the Product interface
Creator (Application)
declares the factory method, which returns an object of type
Product. Creator may also define a default implementation
of the factory method that returns a default
ConcreteProduct object.
may call the factory method to create a Product object
ConcreteCreator (MyApplication)
overrides the factory method to return an instance of a
ConcreteProduct
Factory Method - Consequences
Advantage
eliminates the need to bind application specific classes
into your code; your code deals with Product interface
implemented by ConcreteProduct subclasses
Potential disadvantage
clients might have to subclass the Creator class just to
create a particular (I.e., 1) ConcreteProduct object
Provides hooks for subclasses
Factory Method gives subclasses a hook for providing an
extended version of an object
Connects parallel class hierarchies
see next slide for example
Connecting parallel hierarchies
Manipulator
Figure Client DownClick()
CreateManipulator() Drag()
LineManipulator TextManipulator
LineFigure TextFigure
DownClick() DownClick()
CreateManipulator() CreateManipulator()
Drag() Drag()
creates
creates
Localizes knowledge of which classes belongs together
Factory Method - Implementation
Two major varieties
Creator declares ABSTRACT factory method,
ConcreteCreator implements it
Creator defines a default implementation for factory method
Parameterized factory methods
lets the factory method to create multiple kinds of objects
factory methods takes a parameter: a kind of object to create
all products have to share a Product interface
Parameterized factory methods
class Creator {
public:
virtual Product* Create(ProductId);
};
Product* Creator::Create(ProductId id) {
if (id == MINE) return new MyProduct;
if (id == YOURS) return new YourProduct;
return 0;
}
Product* MyCreator::Create(ProductId id) {
if (id == THEIRS) return new TheirProduct;
return Creator::Create(id);
}
Language-specific variants
C++
“Lazy evaluation”
class Creator {
public:
Product* GetProduct();
protected:
virtual Product* CreateProduct();
private:
Product* _product;
};
Product* Creator::GetProduct() {
if (_product == 0)
_product = CreateProduct();
return _product;
}
Using templates to avoid subclassing
class Creator {
public:
virtual Product* CreateProduct() = 0;
};
template <class TheProduct>
class StandartCreator : public Creator {
public:
virtual Product* CreateProduct();
};
template <class TheProduct>
Product*
StandartCreatot<TheProduct>::CreateProduct(){
return new TheProduct;
}