Design Patterns
Design Patterns
Rambabu Piridi
1
What is a Pattern?
2
Gang of Four
Erich Gamma
Richard Helm
Ralph Johnson
John Vlissides
3
Definition
"Each pattern describes a problem which occurs over and over again in our
environment, and then describes the core of the solution to that problem, in
such a way that you can use this solution a million times over, without ever
doing it the same way twice"
4
Why Design Patterns?
5
Coupling Vs Cohesion
Coupling:
When two units depend on each other, it's called coupling, and it's a bad thing.
You can't understand one unit without understanding the other, which makes maintenance difficult
DCC Device Management Drawbacks of high Coupling:
Hard to understand.
Hard to locate faults.
Difficult to extend or enhance.
Cannot be reused.
Expensive to perform maintenance.
User Management
6
Coupling Vs Cohesion Contd.
User Management
7
Coupling Vs Cohesion Contd.
Cohesion:
Each function should do only one thing. class Dog
{
void doAction (int number)
{
class Dog
if( number==1)
{
jump();
void doAction (int number)
if( number==2)
{
bark();
if( number==1)
}
//Jump code goes here
void jump(){
if( number==2)
--
//Bark code goes here }
} void bark(){
} --
}
}
8
Pattern Classification
1. Creational Patterns
2. Structural Patterns
3. Behavioral Patterns
9
Creational Patterns
1. Factory Method
2. Abstract Factory
3. Builder
4. Prototype
5. Singleton
10
Creational Patterns Types
Class creational patterns use inheritance to vary the class that is instantiated.
Object creational patterns delegate instantiation to another object.
The difference between class patterns and object patterns is that class patterns
describe how inheritance can be used to provide more useful program interfaces.
Object patterns, on the other hand, describe how objects can be composed into
larger structures using object composition, or the inclusion of objects within other
objects.
11
Structural Patterns
Structural patterns describe how classes and objects can be combined to form
larger structures.
ease the design by identifying a simple way to realize relationships between
entities.
the way objects are connected with other objects to ensure that changes in
the system don’t require changes to those connections.
1. Adapter
2. Bridge
3. Composite
4. Decorator
5. Flyweight
6. Façade
7. Proxy
12
Behavioral Patterns
Behavioral patterns are those patterns that are most specifically concerned with
communication between objects.
Behavioral class patterns use inheritance to distribute behavior between classes.
Behavioral object patterns use object composition rather than inheritance.
1. Command
2. Interpreter
3. Iterator
4. Mediator
5. Memento
6. Observer
7. State
8. Strategy
9. Template
10. Visitor & Chain of Responsibility.
13
Classification of GoF Design Pattern
14
Design Pattern Space
Purpose
Crerational Structural Behavioral
Interpreter
Class Factory Method Adapter (Class) Template Method
Chain of Responsibility
Command
Scope Adapter (Object) Iterator
Bridge Mediator
Composite Memento
Abstract Factory Decorator Observer
Builder Façade State
Prototype Flyweight Strategy
Object Singleton Proxy Visitor
15
Patterns Periodic Table.
The holy
The holy origins.
Structural
FM A
Factory
Adapter
Method
The holy
PT S Behaviors CR CP D
Chain of
Prototype Singleton Composite Decorator
Responsibility
AF TM CD MD O IN PX F
Abstract Template
Command Mediator Observer Interpreter Proxy Facade
Factory Method
BU SR MM ST IT V FL BR
Builder Strategy Memento State Iterator Visitor Flyweight Bridge
16
Need for this session
17
Patterns Implemented in JDK
1. Decorator.
2. Composite
3. Strategy
4. Factory
5. Iterator
6. Observer
7. Singleton
8. Prototype
9. Command
10. Adapter
11. Proxy
12. Bridge
13. Facade
18
Decorator Pattern
19
Inheritance Vs Composition
Composition
- Models “has-a” relationship.
- Kind of black-box reuse.
Inheritance
- Models “is-a” relationship.
- Kind of white-box reuse.
Similarities
- Both of them are for re-using functionalities.
20
Advantages
Composition
- Delegation allows composition to be as powerful as Inheritance.
- Creation of back-end objects can be delayed until we need them.
Inheritance
- Easy to use.
- Done statically at run-time.
21
Disadvantages
Composition
- Hard to understand the code.
- Delegation will be slower than Dynamic Binding.
- Delegation requires more code to be written which intern results in
more objects getting instantiated.
Inheritance
- Dependent on parent class implementation.
- Change in the super class can ripple down the inheritance hierarchy
to sub classes.
22
UML Class Diagram
Component <<Interface>>
ConcreteComponent Decorator
Component: component
ConcreteDecorator1 ConcreteDecorator2
23
General Implementation
Java Design Patterns suggest that Decorators should be abstract classes and
the concrete implementation should be derived from them.
24
Decorator contd.
FileInputStream
Java
Program
25
Decorator contd.
BufferedReader
FileInputStream
Java
Program
InputStreamReader
26
Java implementation
BufferedReader bufferedReader =
new BufferedReader( new InputStreamReader(
new FileInputStream(filePath), encodingType));
27
Decorator contd.
FileReader
Java
Program
LineNumberReader
28
Java Structure
Readable
read()
FileReader Reader
Readable:readable
read() read();
LineNumberReader PushbackReader
readLine();
read();
29
Example - 2.
public interface IComponent {
public interface Decorator extends IComponent {
public void doStuff();
public void addedBehavior();
}
}
public class CComponent implements IComponent{
public void doStuff() {
System.out.println("Do Suff");
} public class Client {
} public static void main (String[] args)
{
public class ConcreteDecorator implements Decorator { IComponent comp = new CComponent();
IComponent component; Decorator decorator = new ConcreteDecorator(comp);
public ConcreteDecorator(IComponent component) { decorator.doStuff();
super(); }
this.component = component; }
}
public void addedBehavior() {
System.out.println ("Decorator does some stuff too");
}
public void doStuff() {
component.doStuff();
addedBehavior();
}
30
Applicability
Use Decorator
31
Advantages
32
Disadvantages
A decorator and its component aren't identical. Thus tests for object type will fail.
33
Composite Pattern
34
UML Class Diagram
Component
Operation(): void
Add (Component)
getChildren()
Leaf Composite
35
General Structure of Composite Pattern
aComponent
Clients use the Component class interface to interact with objects in the composite
structure. If the recipient is a Leaf, then the request is handled directly. If the
recipient is a Composite, then it usually forwards requests to its child components,
possibly performing additional operations before and/or after forwarding.
36
Participants
Component:
declares the interface for objects in the composition.
implements default behavior for the interface common to all classes, as
appropriate.
declares an interface for accessing and managing its child components.
Leaf:
represents leaf objects in the composition. A leaf has no children.
defines behavior for primitive objects in the composition.
Composite:
defines behavior for components having children.
implements child-related operations in the Component interface.
37
General Implementation
38
General Implementation
39
JDK Implementation
JComponent
40
Decorator Vs Composite
41
Composite: Applicability
42
Advantages
It makes clients simpler, since they do not have to know if they are
dealing with a leaf or a composite component.
43
Strategy Pattern
More simply put, an object and its behavior are separated and put into
two different classes.
This allows you to switch the algorithm that you are using at any time.
44
Structure
Context Strategy
ContextInterface AlgorithmInterface ()
45
Participants
Strategy (Compositor):
declares an interface common to all supported algorithms. Context
uses this interface to call the algorithm defined by a ConcreteStrategy.
ConcreteStrategy:
implements the algorithm using the Strategy interface.
Context:
is configured with a ConcreteStrategy object.
maintains a reference to a Strategy object.
may define an interface that lets Strategy access its data.
46
General Implementation
47
General Implementation
48
General Implementation
System.out.println( payer.extortCash());
System.out.println( payer2.extortCash());
System.out.println( payer3.extortCash());
}
49
JDK Structure
Container LayoutManager
50
JDK Implementation
51
JDK Implementation - contd
52
Applicability
if you find yourself thinking that there are two or more ways of
accomplishing some task, a strategy pattern is likely needed.
53
Advantages
54
Disadvantages
55
Factory Pattern
Define an interface for creating an object, but let subclasses decide which
class to instantiate. Factory Method lets a class defer instantiation to
subclasses.
56
UML Class Diagram
Creator
+ factoryMethod: Product
Product ConcreteCreator
+ factoryMethod: Product
57
Participants
Product:
Defines the interface for the type of objects the factory method creates
Creator
Declares the factory method, which returns an object of type Product
ConcreteCreator:
Overrides the factory method to return an instance of a ConcreteProduct
58
General Implementation
59
JDK Implementation
Border b2 = BorderFactory.createEtchedBorder(EtchedBorder.RAISED);
60
JDK Implementation – cont’d
java.util.Calendar.getInstance();
61
Advantages
62
Disadvantages
63
Iterator Pattern
An aggregate object is an object that contains other objects for the purpose
of grouping those objects as a unit. It is also called a container or a
collection.
64
Structure
Client Iterator
Aggregate
First()
CreateIterator()
Next()
IsDone()
CurrentItem()
ConcreteAggregate ConcreteIterator
CreateIterator()
65
Participants
Iterator:
Defines an interface for accessing and traversing elements
ConcreteIterator:
Implements the Iterator interface
Keeps track of the current position in the traversal
Aggregate:
Defines an interface for creating an Iterator object
ConcreteAggregate:
Implements the Iterator creation interface to return an instance of the proper
ConcreteIterator
66
Java Implementation Of Iterator
67
The Enumeration Interface
Correspondences:
68
Applicability
69
Consequences
Benefits
Liabilities
None!
70
Observer Pattern
The key objects in this pattern are subject and observer. A subject may have
any number of dependent observers. All observers are notified whenever the
subject undergoes a change in state. In response, each observer will query the
subject to synchronize its state with the subject's state.
71
Big Picture
Object1
Object2
Subject
Object3
Object4
72
Structure
Subject Observer
registerObserver(observer) notify ()
unregisterObsever(observer)
notifyObservers()
ConcreteObserverA ConcreteObserverB
ConcreteSubject
notify () notify ()
notify ()
73
Participants
Subject:
provides an interface for attaching and detaching Observer objects.
Observer:
defines an updating interface for objects that should be notified
of changes in a subject.
ConcreteSubject:
stores state of interest to ConcreteObserver objects.
sends a notification to its observers when its state changes.
ConcreteObserver:
maintains a reference to a ConcreteSubject object.
implements the Observer updating interface to keep its state
consistent with the subject's.
74
JDK Implementation
75
Issue with Observable pattern
76
JavaBeans component model
77
Advantages of Observer Pattern
Java Message Service (JMS), with its guaranteed delivery, non-local distribution,
and persistence.
78
Complications to watch with Observer Pattern
79
Singleton Pattern
Ensure a class only has one instance, and provide a global point of access to it.
Don't let anyone outside the class create instances of the object.
Singletons are lazily created to reduce memory requirements until needed.
Singletons are only guaranteed to be unique within a given class loader
If you use the same class across multiple distinct enterprise containers,
you'll get one instance for each container.
80
Structure
Singleton
static instance
return instance
getInstance( )
Participants:
Singleton:
defines an getInstance operation that lets clients access its unique instance.
getInstance is a class operation (that is, a static method in Java).
81
General Implementation
82
General Implementation
83
JDK Implementation
Runtime rt = Runtime.getRuntime();
84
Points to ponder
85
Points to ponder
2. We can still be able to create a copy of the Object by cloning it using the
Object’s clone method. This can be done as shown below.
This again violates the Singleton Design Pattern's objective. So to deal with this
we need to override the Object’s clone method which throws a
CloneNotSupportedException exception.
86
Thread-safe implementation
87
Double-checked Locking
When this part becomes hot section (heavily accessed) in your code.
Synchronizing and slowing down all the threads. Every thread enters this critical
section and blocks every other thread from using this section.
88
Double-checked Locking implementation
89
Issues with Singleton
90
Implementing WeakSingleton
91
Implementation Issues
Users of this pattern should be aware of the scope & lifecycle control of the
singleton object.
92
Advantages of Singleton Pattern
93
Disadvantages of Singleton Pattern
Object lifetime. Singleton does not address the issue of deleting the single object.
94
Prototype Pattern
95
Structure
Client Prototype
getInstance( ) Clone()
ConcretePrototype1 ConcretePrototype2
Clone() Clone()
96
UML Diagram
Client Prototype
Copy Data
Return ()
97
General Implementation
98
General Implementation
99
General Implementation
100
JDK Implementation
101
Using clone()
102
Applicability
103
Advantages
It hides the concrete product classes from the client, thereby reducing the
number of names clients know about.
Adding and removing products at run-time.
Specifying new objects by varying values.
Reduced sub-classing.
Configuring an application with classes dynamically.
104
Disadvantages
The drawback is that each subclass of Prototype must implement the Clone
operation, which may be difficult.
105
Command Pattern
It lets you give the client the ability to make requests without knowing
anything about the actual action that will be performed, and allows you to
change that action without affecting the client program in any way.
106
Structure
Invoker <<Interface>>
Command
execute()
Receiver ConcreteCommand
action() execute()
107
http://www.allappforum.com/java_design_patterns/command_pattern.htm
108
JDK Implementation
When you build a Java user interface, you provide menu items, buttons, and
checkboxes and so forth to allow the user to tell the program what to do.
Let's suppose we build a very simple program that allows you to select the
menu items File | Open and File | Exit, and click on a button marked Red
which turns the background of the window red.
The program consists of the File Menu object with the mnuOpen and
mnuExit MenuItems added to it.
109
JDK Implementation cont’d
110
Good for Small Examples but…
This approach works fine as long as there are only a few menu items
and buttons, but
– when you have dozens of menu items and several buttons, the
actionPerformed code can get pretty unwieldy.
In addition, this really seems a little inelegant, since we'd really hope
that in an object-oriented language like Java, we could avoid a long
series of if statements to identify the selected object.
Instead, we'd like to find a way to have each object receive its
commands directly.
111
Our goal..
112
The Command Object
One way to assure that every object receives its own commands directly is to
One important purpose of the Command pattern is to keep the program and
user interface objects completely separate from the actions that they initiate.
113
The Command Pattern in Java
114
Providing Undo
Another of the main reasons for using Command design patterns is that they
provide a convenient way to store and execute an Undo function. Each
command object can remember what it just did and restore that state when
requested to do so if the computational and memory requirements are not too
overwhelming.
http://www.javaworld.com/javaworld/jw-06-1998/jw-06-undoredo.html?page=1#undo
115
Consequences of Command Pattern
1. Command decouples the object that invokes the operation from the one
that knows how to perform it.
4. It's easy to add new Commands, because you don't have to change
existing classes.
116
Disadvantage of Command Pattern
117
Adapter Pattern
Two-prong wall outlet three-prong plug
118
Applicability
you need to use several existing subclasses, but it's impractical to adapt
their interface by sub-classing every one. An object adapter can adapt
the interface of its parent class.
119
Structure
Adapter
Request() SpecificRequest()
120
Participants
Client:
Collaborates with objects conforming to the Target interface.
Target:
Defines the domain-specific interface that Client uses.
Adaptee:
defines an existing interface that needs adapting.
Adapter:
Adapts the interface of Adaptee to the Target interface.
Collaboration:
121
Implementation
In the first case, we derive a new class from the nonconforming one and add
the methods we need to make the new derived class match the desired
interface.
The other way is to include the original class inside the new one and create the
methods to translate calls within the new class.
122
Adapter Types
2. Object Adapter
123
Class Adapter
Adaptee1 AdapteeN
+method1() +methodN()
Client Adapter
+adapter Adapter
doWork() methodA()
Method1()
adapter.methodA() .
.
methodN()
124
Object Adapter
Adaptee
+methodB()
Client Adapter
doWork() +methodA()
adapter.methodA() adaptee.methodB()
125
Class Adapter Vs Object Adapter
Won’t work when we want to adapt a class and all of its subclasses,
since you define the class it derives from when you create it.
Lets the adapter change some of the adapted class’s methods but still
allows the others to be used unchanged.
126
Two Way Adapters
i.e. A two-way adapter supports both the Target and the Adaptee interface. It
allows an adapted object (Adapter) to appear as an Adaptee object or a Target
object.
Easily carried out using a class adapter, since all of the methods of the base
class are automatically available to the derived class.
However, this can only work if you do not override any of the base class’s
methods with ones that behave differently.
Java has yet another way for adapters to recognize which of several classes
it must adapt to: Reflection.
127
Implementing Two Way Adapters
triple.insertTriple();
128
Implementing Two Way Adapters
Implement Later
from Eclipse
130
Adapters in Java
In a broad sense, there are already a number of adapters built into the
Java language. In this case, the Java adapters serve to simplify an
unnecessarily complicated event interface. One of the most commonly used
of these Java adapters is the WindowAdapter class.
131
Advantages
Allow swing trees to manipulate and display any type of tree structure.
Disadvantages
hierarchy hardening
132
Proxy Pattern
Proxy:
- Is a class functioning as an interface to Object.
- A person authorized to act for another person
In situations where multiple copies of a complex object must exist the proxy
pattern can be adapted to reduce the application's memory footprint.
i.e provide a surrogate or placeholder for another object to control access to it
If creating an object is expensive in time or computer resources, Proxy allows
you to postpone this creation until you need the actual object.
There are situations in which a client does not or can not reference an
object directly, but wants to still interact with the object . A proxy object can
act as the intermediary between the client and the target object.
133
Real-world Example
134
Real-world Example cont’d
135
Proxy Pattern
Applicability
Motivation
The proxy object has the same interface as the target object.
The proxy holds a reference to the target object and can forward
requests to the target as required (delegation!).
In effect, the proxy object has the authority the act on behalf of the
client to interact with the target object.
136
Types of Proxies
1. Remote Proxy:
Provides a reference to an object located in a different address space on the
same or different machine.
2. Virtual Proxy:
Allows the creation of a memory intensive object on demand. The object will
not be created until it is really needed.
3. Protection (Access) Proxy :
Provides different clients with different levels of access to a target object.
137
Types of Proxies
5. Copy-On-Write Proxy
Defers copying (cloning) a target object until required by client actions.
Really a form of virtual proxy.
6. Cache Proxy
Provides temporary storage of the results of expensive target operations so
that multiple clients can share the results.
7. Firewall Proxy
Protects targets from bad clients (or vice versa)
8. Synchronization Proxy
Protects targets from bad clients (or vice versa)
138
Structure
Client Subject
Request()
RealSubject Proxy
Request() Request ()
Object Diagram:
Client
Subject Proxy
realSubject RealSubject
139
Participants
Proxy:
maintains a reference that lets the proxy access the real subject.
provides an interface identical to Subject's so that a proxy can by
substituted for the real subject.
controls access to the real subject and may be responsible for creating
and deleting it.
Subject:
defines the common interface for RealSubject and Proxy so that a Proxy
can be used anywhere a RealSubject is expected.
RealSubject:
defines the real object that the proxy represents.
140
JDK Implementation
java.util.Vector
Though the Vector class doesn’t directly provide the storage service, the proxy
class manages this service, given the capability to automatically relocate a
bigger array when needed.
The class javax.swing.ImageIcon that could be described as a proxy of the
class java.awt.Image.
141
Example
142
Example Cont’d
Start Start
forward forward
Client Proxy
Stop Stop
143
Applicability
There are four common situations in which the Proxy pattern is applicable.
1. Virtual proxy.
2. Remote proxy.
3. Protective proxy.
4. Smart proxy.
144
Advantages
1. A remote proxy can hide the fact that an object resides in a different
address space.
145
Bridge Pattern
146
Proxy in RMI
147
The Bridge pattern can be found in the separation of the components in java.awt
(e.g., Button and List), and their counterparts in java.awt.peer
148
References
http://www.allappforum.com/
149