Design Patterns David Talby This Lecture n The
Design Patterns David Talby
This Lecture n The Creational Patterns u Builder u Prototype u Factory Method u (Abstract Factory) u Singleton n Choosing Between Them
Creational Patterns n Easily Change: u What gets created? u Who creates it? u When is it created? n n Hide the concrete classes that get created from client code Competing patterns, each with its own strengths
4. Builder n n n 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 n Single Choice Principle u Same reader for all output formats u Output format chosen once in code n Open-Closed Principle u Easy to add a new output format u Addition does not change old code n Dynamic choice of output format
The Solution n We should return a different object depending on the output format: u HTMLDocument, n n n 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 n Here’s the builder’s interface: class Builder { void write. Char(char c) { } void set. Font(Font *f) { } void new. Page() { } }
The Solution III n Here’s a concrete builder: class HTMLBuilder : public Builder { private: HTMLDocument *doc; public: HTMLDocument *get. Document() { return doc; } // all inherited methods here }
The Solution IV n The converter uses a builder: class Converter { void convert(Builder *b) { while (t = read_next_token()) switch (o. kind) { CHAR: b->write. Char(o); FONT: b->set. Font(o); } } } // other kinds…
The Solution V n This is how the converter is used: RTFBuilder *b = new RTFBuilder; converter->convert(b); RTFDocument *d = b->get. Document();
The UML
The Fine Print n n The builder’s interface affects the ease of coding concrete builders Kinds of documents don’t need a common base class Methods in class Builder are empty and not abstract get. Result ()is not always trivial u Optimizations u Lazy Creation
Known Uses n n n Converting to different formats Building a parse tree in a compiler Building a normalized database
5. Prototype n n n Specify the kind of object to create using a prototypical instance For example, a photo/map editor has a palette of tools and objects that can be created How do we have only one class for creations, and parameterize it by the class of objects it initializes?
The Requirements n n n One class for the creation tool Easy to add new objects Dynamic toolbox configuration
The Solution n n Hold a prototype of object to create Creation is by cloning the prototype
The Solution II n n n Less classes in the system Can be even less: same Graphic object with different properties can be used for different tools Tools can be chosen and configured at runtime
The UML
The Fine Print n n Prototype Manager - a runtime registry of prototype can handle dynamically linked classes Java, Small. Talk, Eiffel provide a default clone() method. C++ has copy constructors All of these are shallow by default When implementing deep clone, beware of circular references!
Known Uses n n Toolboxes / Palettes Supporting dynamically defined debuggers in a uniform GUI EJB / COM Servers Basically a plug-in mechanism
6. Factory Method n n n Let subclasses decide which objects to instantiate For example, a framework for a windowing application has a class Application which must create an object of class Document But the actual applications and documents are not written yet!
The Solution n Separate creation into a method
Second Variant n n n A remote services package has a Remote. Service class that returns objects of class Proxy to client A few clients wish to write a more potent Cached. Proxy How do we support this without much hassle?
Second Variant Solution n Separate creation into a method Remote. Service will have a virtual method called Create. Proxy() Write Cached. Proxy, then write: class Cached. Remote. Service : public Remote. Service { Proxy* create. Proxy(. . . ) { return new Cached. Proxy(. . . ); } }
The UML
The Fine Print n n n Two Variants: Is the factory method abstract or not? Good style to use factory methods even for a slight chance of need Parameterized factory methods make it easy to add created products without affecting old code Product* create. Product(int id) { switch (id) {. . . } }
The Fine Print II n C++ warning: You can’t call a factory method from a constructor! u Use lazy initialization instead Product* get. Product() { if (_product == NULL) _product = create. Product(); return _product; } n Use templates to avoid subclassing u u Application<Excel. Document> complex<float>, complex<double>
Known Uses n n A very common pattern Framework classes u Application, n Document, View, . . . Changing default implementations u Proxy, Parser, Memory. Manager, …
Pattern of Patterns Encapsulate the varying aspect n Interfaces n Inheritance describes variants n Composition allows a dynamic choice between variants Criteria for success: Open-Closed Principle Single Choice Principle n
A Comparative Example
The Example Problem Maze* Maze. Game: : Create. Maze () { Maze* Room* Door* a. Maze = new Maze; r 1 = new Room(1); r 2 = new Room(2); the. Door = new Door(r 1, r 2); a. Maze->Add. Room(r 1); a. Maze->Add. Room(r 2); r 1 ->Set. Side(North, new Wall); r 1 ->Set. Side(East, the. Door); // set other sides, also for r 2 return a. Maze; }
Enchanted Mazes n How do we reuse the same maze with Enchanted. Room, Trap. Door? u Pass create. Maze an object that can create different maze parts u Pass create. Maze an object that can build a maze and then return it u Pass create. Maze initialized samples of each kind of maze part u Move creation with new to other methods that descendants redefine
1. Abstract Factory n Define a set of interfaces u Door, n Wall, Room, . . . Write families of classes u Simple. Door, Simple. Room, … u Enchanted. Door, n Define an abstract Maze. Factory, and a concrete class for each family u Simple. Factory, n Enchanted. Room, . . . Enchanted. Factory, … Pass create. Maze a factory
Abstract Factory Cons n n n Requires a new factory class for every family Families are defined statically Parts of the complex maze are returned right after creation The client of the factory builds the connections between maze parts Maze stands for any complex object
Builder Pros & Cons n Pros u Each builder can create a totally different kind of object u Object returned only at the end of construction - enables optimization u Especially if object is on network n Cons u Complex Interface to builder
Prototype Pros & Cons n Pros u Less Classes u Prototype can be customized between different creations n Cons u Requires memory to hold prototype u Many prototypes must be passed u Clone() may be hard to implement
Factory Method P&C n Pros u The n simplest design Cons u Requires a new class for every change in creation u Compile-time choice only
The Verdict n n Use Factory Methods when there is little (but possible) chance of change Use Abstract Factory when different families of classes are given anyway Use Prototype when many small objects must be created similarly Use Builder when different output representations are necessary
Some Easy Cases n Dynamic loading of classes whose objects must be created u only n Prototype Creation can be highly optimized once entire structure is known u only Builder
7. Singleton n Ensure that only one instance of a class exists, and provide a global access point to it For example, ensure that there’s one Window. Manager, File. Manager or Print. Spooler object in the system Desirable to encapsulate the instance and responsibility for its creation in the class
The Solution n O-O languages support methods shared by all objects of a class in C++ and Java u class methods in Small. Talk, Delphi u static n n n The singleton class has a reference to its single instance The instance has a getter method which initializes it on the first request The class’s constructor is protected to prevent creating other instances
The Solution class Spooler { public: static Spooler* instance() { if (_instance == NULL) _instance = new Spooler(); return _instance; } protected: Spooler() {. . . } private: static Spooler* _instance = 0; }
The UML
The Fine Print n n Passing arguments for creation can be done with a create(. . . ) method Making the constructor public makes it possible to create other instance except the “main” one u Not n n a recommended style instance() can manage concurrent access or manage a list of instances Access to singletons is often a bottleneck in concurrent systems
Known Uses n n n Every system has singletons! Window. Manager, Printer. Manager, File. Manager, Security. Manager, . . . Class Application in a framework Log and error reporting classes With other design patterns
Summary: Connections n n n “Abstract Factories are usually implemented using Factory Methods but can also use Prototypes” “Builders and Abstract Factories are often Singletons” “Builders can use Abstract Factories to enjoy best of both worlds”
- Slides: 46