Patterns 2 Creational
Patterns 2 Creational
Patterns
David Talby
This Lecture
■ The Creational Patterns
◆ Builder
◆ Prototype
◆ Factory Method
◆ (Abstract Factory)
◆ Singleton
■ Choosing Between Them
Creational
Patterns
■ Easily Change:
◆ What gets created?
◆ Who creates it?
◆ When is it created?
■ Hide the concrete classes that get
created from client code
■ Competing patterns, each with its
own strengths
4. Builder
■ Separate the specification of how
to construct a complex object from
the representation of the object
■ For example, a converter reads
files from one file format
■ It should write them to one of
several output formats
The
Requirements
■ Single Choice Principle
◆ Same reader for all output formats
◆ Output format chosen once in code
■ Open-Closed Principle
◆ Easy to add a new output format
◆ Addition does not change old code
■ Dynamic choice of output format
The Solution
■ We should return a different object
depending on the output format:
◆ HTMLDocument, RTFDocument, …
■ Separate the building of the output
from reading the input
■ Write an interface for such a builder
■ Use inheritance to write different
concrete builders
The Solution II
■ Here’s the builder’s interface:
class Builder {
void writeChar(char c) { }
void setFont(Font *f) { }
void newPage() { }
}
The Solution III
■ Here’s a concrete builder:
class HTMLBuilder
: public Builder
{
private:
HTMLDocument *doc;
public:
HTMLDocument *getDocument() {
return doc;
}
// all inherited methods here
}
The Solution IV
■ The converter uses a builder:
class Converter
{
void convert(Builder *b) {
while (t = read_next_token())
switch (o.kind) {
CHAR: b->writeChar(o);
FONT: b->setFont(o);
// other kinds…
}
}
}
The Solution V
■ This is how the converter is used: