Creational Design Patterns Structural Design Patterns Behavioral Design Patterns Applying Design Patterns
Creational Design Patterns Structural Design Patterns Behavioral Design Patterns Applying Design Patterns
Creational Design Patterns Structural Design Patterns Behavioral Design Patterns Applying Design Patterns
Creational Design Patterns Structural Design Patterns Behavioral Design Patterns Applying Design Patterns
Creational patterns
Creational design patterns abstract the instantiation process. There are two recurring themes in these patterns.
First, they all encapsulate knowledge about which concrete classes the system uses. Second, they hide how instances of these classes are created and put together.
Abstract Factory
The Client remains blissfully unaware of the various concrete classes in this example. Client code deals with the simpler, abstract, general case.
SomeApp
<<Interface>>
Shape
Square
<<creates>>
Circle
10
11
Abstract Factory
Intent:
Provide an interface for creating families of related or dependent objects without specifying their concrete classes.
13
the factory method in the MyApplication class: public Document CreateDocument() { return new MyDocument();} client code: public Application app1; app1 = new MyApplication(); app1.CreateDocument();
15
Factory Method
Intent:
Define an interface for creating an object, but let subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses.
Structure
16
Solution:
to configure the RTFReader class with a TextConverter object that converts RTF to another textual representation. Subclasses of TextConverter specialize in different conversions and formats.
17
Builder - Example
18
Builder
Intent: Separate the construction of a complex object from its representation so that the same construction process can create different representations. Structure
19
Builder
Collaborations :
The client creates the Director object and configures it with the desired Builder object. Director notifies the builder whenever a part of the product should be built. Builder handles requests from the director and adds parts to the product. The client retrieves the product from the builder.
20
game.CreateMaze(builder);
maze = builder.GetMaze();
Bulider Code: Director Code: class MazeBuilder { Maze* MazeGame::CreateMaze (MazeBuilder& public: builder) { virtual void BuildMaze() { } builder.BuildMaze(); virtual void BuildRoom(int room) { } builder.BuildRoom(1); virtual void BuildDoor(int roomFrom, int roomTo) builder.BuildRoom(2); {} builder.BuildDoor(1, 2); virtual Maze* GetMaze() { return 0; } return builder.GetMaze(); protected: } MazeBuilder(); }; ConcreteBuilder Code: class StandardMazeBuilder : public MazeBuilder { public: StandardMazeBuilder(); virtual void BuildMaze(); virtual void BuildRoom(int); virtual void BuildDoor(int, int); virtual Maze* GetMaze(); private: Direction CommonWall(Room*, Room*); Maze* _currentMaze; }; Object Oriented Analysis and Design 21
Solution:
making GraphicTool create a new Graphic by copying or "cloning" an instance of a Graphic subclass. We call this instance a prototype.
22
Prototype
Intent: Specify the kinds of objects to create using a prototypical instance, and create new objects by copying this prototype.
Structure
A client asks a prototype to clone itself
23
Prototype
Discussion:
Declare an abstract base class that specifies a pure virtual "clone" method, and, maintains a dictionary of all "cloneable" concrete derived classes. Any class that needs a "polymorphic constructor" capability: derives itself from the abstract base class, registers its prototypical instance, and implements the clone() operation. The client then, instead of writing code that invokes the "new" operator on a hard-wired class name, calls a "clone" operation on the abstract base class, supplying a string or enumerated data type that designates the particular concrete derived class desired.
24
25
Singleton
Intent: Ensure a class only has one instance, and provide a global point of access to it.
Structure
26
Singleton - example
public abstract class ForumFactory { private static Object initLock = new Object(); private static String className = "com.abc.forum.db.DbForumFactory"; private static ForumFactory factory = null; public static ForumFactory getInstance(Authorization authorization) { if (authorization == null) {return null;} if (factory == null) {// Singleton pattern synchronized(initLock) { if (factory == null) { ...... try { Class c = Class.forName(className); factory = (ForumFactory)c.newInstance(); catch (Exception e) {return null;} } } } ..... }
Object Oriented Analysis and Design
27
28
Switch
Simple table lamp
+turnOn +turnOff
29
Light
+turnOn +turnOff
Fan FanSwitch
+turnOn +turnOff
30
Switch
Switchable
+turnOn +turnOff
Light
+turnOn +turnOff
ABSTRACT SERVER solution to the Table Lamp problem It satisfies both the DIP and the OCP But there is a potential violation of the Single-Responsibility Principle (SRP: A class should only one reason to change) We have bound together two things, Light and Switchable, that may
not change for the same reasons. What if we purchased Light from a third party?
Object Oriented Analysis and Design
31
Switch
Switchable
+turnOn +turnOff
Light Adapter
+turnOn +turnOff
<<delegates>>
Light
+turnOn +turnOff
Solving the Table Lamp problem with the object form ADAPTER Note:
Adapter dont come cheap. You dont want to use adapters all the time The ABSTRACT SERVER solution is quite appropriate for most situations. In fact, even the simple solution is pretty good unless you happen to know that there are other objects for switch to control.
Object Oriented Analysis and Design
32
Switch
Switchable
+turnOn +turnOff
Light Adapter
+turnOn +turnOff
Light
+turnOn +turnOff
Solving the Table Lamp problem with the class form ADAPTER
33
Adapter Pattern
Adapter Pattern 1) Convert the interface of a class into another interface expected by the client. Adapter lets classes work together that couldnt otherwise because of incompatible interfaces 2) Used to provide a new interface to existing legacy components (Interface engineering, reengineering). 3) Also known as a wrapper 4) Two adapter patterns: Class adapter: - Uses multiple inheritance to adapt one interface to another Object adapter: - Uses single inheritance and delegation 5) We will mostly use object adapters and call them simply adapters
Object Oriented Analysis and Design
34
Adapter
Intent:
Convert the interface of a class into another interface clients expect. Adapter lets classes work together that couldn't otherwise because of incompatible interfaces.
Structure
35
36
Delegation is used to bind an Adapter and an Adaptee 1) Interface inheritance is use to specify the interface of the Adapter class. 2) Adaptee, usually called legacy system, pre-exists the Adapter. 3) Target may be realized as an interface in Java.
Object Oriented Analysis and Design
37
Adapter - Example
Client Code:
Adaptee a = new Adaptee(); Target t = new Adapter(a); public void test() { t.request(); }
Target Code: Adaptee Code:
System.out.println("Adaptee: SpecificRequest");
} }
Adapter Code:
class Adapter extends Target { private Adaptee adaptee; public Adapter(Adaptee a) { adaptee = a;} public void request() { adaptee.specificRequest();} }
Object Oriented Analysis and Design
38
Client
<<Interface>>
Enumeration
ServicesEnumeration
RegiteredServices
hasMoreElements() nextElement()
Object Oriented Analysis and Design
hasMoreElements() nextElement()
-adaptee
numServices() getService()
39
40
Modem
+dial +hangup +send +receive
Modem Clients
Ernies Modem
Modem Problem
Problem:
Suppose that there were hundreds of modem clients all making happy use of the Modem interface. Now suppose that customer have given us a new kind of modem that dont dial - dedicated modem. There are several new applications (Ded Users) that use these dedicated modems and dont bother to dial. All the current modem clients to be able to use these dedicated modems and neednt to modify their applications.
Object Oriented Analysis and Design
41
Dialler
+dial +hangup
<<Interface>>
Ernies Modem
Modem Clients
Modem
+send +receive
Ded Users
Problem:
Dedicated Modem
42
Modem
+dial +hangup +send +receive
Modem Clients
Ernies Modem
Ded Users
Dial and Hangup are implemented to simulate connection state. Send and Receive are delegated to DedicatedModem
43
DedicatedModem
Hayes Dedicated Modem USR Dedicated Modem Ernies Dedicated Modem
44
ModemConnectionCo ntroller #dialImp #hangupImp #sendImp #receiveImp +dial +hangup +send +receive <<delegates>>
Ded Users
Ford
Toyota
Sporty
Truck
SportyFord
ToyotaTruck
FordTruck
SportyToyota
46
Car
CarManufacturer
Sporty
Object Oriented Analysis and Design
Truck
47
Ford
Toyota
48
49
: Part
Contains
: Assembly
Contains
: Part
: Part
Part
Assembly
0..1
+ cost() : double
+ cost() : double
53
55
56
58
Suppose you have a user interface toolkit and you wish to make a border or scrolling feature available to clients without defining new subclasses of all existing classes. The client "attaches" the border or scrolling responsibility to only those objects requiring these capabilities. Widget* aWidget = new BorderDecorator(
Stream Example
cascading responsibilities on to an output stream
Stream* aStream = new CompressingStream( new ASCII7Stream( new FileStream( "fileName.dat" ))); aStream->putString( "Hello world" );
59
+component component.draw()
super.draw() drawBorder()
Decorator subclasses are free to add operations for specific functionality. For example, ScrollDecorator's ScrollTo operation lets other objects scroll the interface if they know there happens to be a ScrollDecorator object in the interface.
Object Oriented Analysis and Design
60
61
Structure
Structure
62
while(in.available() != 0)
System.out.print((char)in.readByte()); }
}
Object Oriented Analysis and Design
63
64
66
Defer creation and initialization to the time you need the object Reduce the cost of access to objects
Use another object (the proxy) that acts as a stand-in for the real object The proxy creates the real object only if the user asks for it
67
68
Problem
You need to support resource-hungry objects, and you do not want to instantiate such objects unless and until they are actually requested by the client.
Structure
69
Proxy and ProxyBase Code: interface ProxyBase { void f(); void g(); void h();} class Proxy implements ProxyBase { private ProxyBase implementation; public Proxy() { implementation = new Implementation(); } public void f() {implementation.f();} public void g() {implementation.g();} public void h() {implementation.h();} }
class Implementation implements ProxyBase { public void f() {System.out.println("Implementation.f()");} public void g() {System.out.println("Implementation.g()");} public void h() {System.out.println("Implementation.h()");} }
Object Oriented Analysis and Design
70
71
if(rr == null) return null; return new ConnectionProxy(rr);} private static class ConnectionProxy implements Connection { private PoolManager.ReleasableReference implementation;
public ConnectionProxy(PoolManager.ReleasableReference rr) {implementation = rr;}
public Object get() {return ((Connection)implementation.getReference()).get();} public void set(Object x) {((Connection)implementation.getReference()).set(x);} public void release() { implementation.release(); }
}
}
Object Oriented Analysis and Design
72
class DataPoint { private static int count = 0; private int id = count++; private int i; private float f; public int getI() { return i; } public void setI(int i) { this.i = i; } public float getF() { return f; } public void setF(float f) { this.f = f; } public String toString() {return "id: " + id + ", i = " + i + ", f = " + f;} } This program may result in excessive slowness or running out of memory. public class ManyObjects { static final int size = 1000000; public static void main(String[] args) { DataPoint[] array = new DataPoint[size]; for(int i = 0; i < array.length; i++) array[i] = new DataPoint(); for(int i = 0; i < array.length; i++) { DataPoint dp = array[i]; dp.setI(dp.getI() + 1); dp.setF(47.0f); } System.out.println(array[size -1]); } Object Oriented Analysis and Design 75 }
Now all the data is in ExternalizedData each call to a FlyPoint method must include the index into ExternalizedData
Object Oriented Analysis and Design
76
Structure
77
78
Observer pattern
Also known as: Publish / Subscribe, Model / View, and Source / Listener. Motivation: Two File Managers are both observing the same Directory; the user deletes a subdirectory using File Manager A; we want File Manager B to immediately and automatically get updated, reflecting the change... Applicability: When there are multiple views of a model (subject) that need to stay in sync. No view should know about any other. When an object needs to communicate to other objects of unknown type (but known Observer interface) it can notify them. Pros: Promotes loose coupling between objects. Excellent communication protocol. Avoids polling Cons: None. Knowledge of this pattern is essential.
80
Observer pattern
Intent: Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically.
81
82
83
84
85
86
87
import com.bruceeckel.swing.*;
public class Button2 extends JApplet { JButton b1 = new JButton("Button 1"), b2 = new JButton("Button 2"); JTextField txt = new JTextField(10);
Event Sources
Events
public void actionPerformed(ActionEvent e){ String name = ((JButton)e.getSource()).getText(); txt.setText(name);} } BL al = new BL(); public void init() { b1.addActionListener(al); b2.addActionListener(al); cp.add(b1); cp.add(b2); cp.add(txt); } public static void main(String[] args) {Console.run(new Button2(), 200, 75);} }Object Oriented Analysis and Design
88
Event handle r
Event Sources
EventListener
(from util)
handle r
EventObject
(from util)
AbstractButton
(from swing)
(from event)
AWTEvent
(from awt)
Events
BL
(from Button2)
ActionEvent
(from event)
90
91
92
Command object:
class Hello implements Command {public void execute() {System.out.print("Hello ");}} class World implements Command {public void execute() {System.out.print("World! ");}} class IAm implements Command { public void execute() {System.out.print("I'm the command pattern!");} }
93
Command pattern
Intent
Encapsulate a request as an object, thereby letting you parameterize clients with different requests, queue or log requests, and support undoable operations.
Structure
95
Problem
How to decouple the button that initiates the help request from the objects that might provide help information?
Solution
to decouple senders and receivers by giving multiple objects a chance to handle a request. The request gets passed along a chain of objects until one of them handles it. The first object in the chain receives the request and either handles it or forwards it to the next candidate on the chain, which does likewise. The object that made the request has no explicit knowledge of who will handle it
Object Oriented Analysis and Design
97
98
class HelpHandler { private: HelpHandler* _successor; public: HelpHandler ( HelpHandler* h, Topic t ) : _successor(h), _topic(t) { } virtual void HandleHelp() { if (_successor != 0) { _successor->HandleHelp(); } } .};
class Widget : public HelpHandler {}; class Button : public Widget { public: virtual void HandleHelp() { if (HasHelp()) { // offer help on the button } else { HelpHandler::HandleHelp(); //the request gets forwarded to the successor using the HandleHelp operation in HelpHandler. }} ; class Dialog : public Widget { public: virtual void HandleHelp() { if (HasHelp()) { // offer help on the button } else { HelpHandler::HandleHelp();}} ; class Application : public HelpHandler { public: Application(Topic t) : HelpHandler(0, t) { } virtual void HandleHelp() { // show a list of help topics }};
Object Oriented Analysis and Design
99
100
101
Hayes
Zoom
Ernie
102
Hayes
Zoom
Ernie
UnixModemConfigura tor
105
<<degenerate>> ModemVisitor
UnixModemConfigura tor
Zoom
Ernie
<<interface>> ZoomVisitor
+visit(Zoom)
106
<<interface>> ErnieVisitor
+visit(Ernie)
108
109
Visitor pattern
111
Visitor Pattern
Intent
Represent an operation to be performed on the elements of an object structure. Visitor lets you define a new operation without changing the classes of the elements on which it operates.
Structure
A client that uses the Visitor pattern must create a ConcreteVisitor object and then traverse the object structure, visiting each element with the visitor. When an element is visited, it calls the Visitor operation that corresponds to its class. The element supplies itself as an argument to this operation to let the visitor access its state, if necessary.
112
113
114
115
116
117
118
119
120
OpenDocument defines each step for opening a document. We call OpenDocument a template method. A template method defines an algorithm in terms of abstract operations that subclasses override to provide concrete behavior.
Object Oriented Analysis and Design
121
public class ftocTemplateMethod extends Application { private InputStreamReader isr; private BufferedReader br;
We can rewrite the ftoc class by inheriting from Application and just filling in the abstract methods
public static void main(String[] args) throws Exception { (new ftocTemplateMethod()).run(); } protected void init() {isr = new InputStreamReader(System.in); br = new BufferedReader(isr); } protected void idle() { String fahrString = readLineAndReturnNullIfError(); if (fahrString == null || fahrString.length() == 0) setDone(); else {double fahr = Double.parseDouble(fahrString); double celcius = 5.0/9.0*(fahr-32); System.out.println("F=" + fahr + ", C=" + celcius);} }
124
125
126
We can avoid these problems by defining classes that encapsulate different linebreaking algorithms.
127
ApplicationR unner
+run
Application
+init +idle +cleanup +done : boolean
public class ApplicationRunner { private Application itsApplication = null; public ApplicationRunner(Application app){ itsApplication = app; } public void run() { itsApplication.init(); while (!itsApplication.done()) itsApplication.idle(); itsApplication.cleanup(); } Object Oriented Analysis and Design 129 }
focStrategy
130
131
132
Strategy is similar to Bridge; same basic structure; very different intent. The Strategy pattern is also similar to State, which allows a class to be configured with different behaviors from which it can select whenever it makes an interesting state transition.
Object Oriented Analysis and Design
133
134
135
In this example, notice that clients of NumberCruncher do not know about the different crunch algorithms. The NumberCruncher.crunch() method is free to decide which CrunchImpl to use at any time; new algorithms can be easily added.
Object Oriented Analysis and Design
136
137
138
The key idea is to introduce an abstract class called TCPState to represent the states of the network connection.
The TCPState class declares an interface common to all classes that represent different operational states. Subclasses of TCPState implement state-specific behavior.
139
140
<<interface>>
TurnstileState
+coin (Turnstile) +pass (Turnstile)
141
class UnlockedTurnstyleState implements TurnstyleState { public void coin(Turnstyle t) { t.thankyou(); } public void pass(Turnstyle t) { t.setLocked(); t.lock(); } }
Structure
143
144
145
146
147
import java.util.*; public class TypedIterator implements Iterator { private Iterator imp; private Class type; public TypedIterator(Iterator it, Class type) { imp = it; this.type = type;} public boolean hasNext(){return imp.hasNext();} public void remove() { imp.remove(); } public Object next() { Object obj = imp.next(); if(!type.isInstance(obj)) throw new ClassCastException( "TypedIterator for type " + type + " encountered type: " + obj.getClass()); return obj; } }
148
Structure
149
A memento is an object that stores a snapshot of the internal state of another objectthe memento's originator.
The undo mechanism will request a memento from the originator when it needs to checkpoint the originator's state. The originator initializes the memento with information that characterizes its current state. Only the originator can store and retrieve information from the mementothe memento is "opaque" to other objects.
150
151
private class Memento implements java.io.Serializable{ private int number; private File file = null; public Memento( Originator o){ number = o.number; file = o.file;} }
152
Memento
Intent: Save an objects state without violating the principle of encapsulation. Applicability: The state of an object must be saved (by a client) so that it can be restored later. The Memento object contains all the necessary state information. l This is another way to implement undo. l Example: Java Beans save their state to a .ser file after being configured. l How is it possible, in Java & C++, for methods & data in the class Memento to be available to SomeClass, but not to Clients?
153
154
155
Structure
Colleagues send and receive requests from a Mediator object. The mediator implements the cooperative behavior by routing requests between the appropriate colleague(s).
156
157