0% found this document useful (0 votes)
262 views

Design Patterns

Design patterns are standardized, reusable solutions to common problems in software design. The Gang of Four book documented 23 design patterns, categorized into creational, structural, and behavioral patterns. Creational patterns deal with object creation mechanisms, structural patterns describe how classes and objects can be combined, and behavioral patterns are concerned with communication between objects. Design patterns provide proven solutions to recurring problems and make software design communication more efficient.

Uploaded by

vivekrajk
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
262 views

Design Patterns

Design patterns are standardized, reusable solutions to common problems in software design. The Gang of Four book documented 23 design patterns, categorized into creational, structural, and behavioral patterns. Creational patterns deal with object creation mechanisms, structural patterns describe how classes and objects can be combined, and behavioral patterns are concerned with communication between objects. Design patterns provide proven solutions to recurring problems and make software design communication more efficient.

Uploaded by

vivekrajk
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 149

By

Rambabu Piridi

1
What is a Pattern?

A pattern is a way of doing something, or a way of pursuing an intent. (or)


Standardized way of achieving certain aim.
This idea applies to cooking, making fireworks, developing software, and to any
other craft.
Christopher Alexander (civil engineer ) was one of the first writers to encapsulate
a craft's best practices by documenting its patterns.

2
Gang of Four

Design Patterns: Elements of Reusable Object-Oriented Software


is a software engineering book describing recurring solutions to common problems
in software design.

Erich Gamma
Richard Helm
Ralph Johnson
John Vlissides

3
Definition

Christopher Alexander said..

"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"

To put it simply, time-tested solutions to recurring design problems.

4
Why Design Patterns?

Design patterns have two major benefits.


 they provide you with a way to solve issues related to software
development using a proven solution. The solution facilitates the
development of highly cohesive modules with minimal coupling.
 design patterns make communication between designers more efficient.

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.

DCC Device Management


Benefits of Low-coupling:
 Easy maintenance.
 Software reuse.
 Classes easy to understand.

User Management

A design objective is to minimize coupling, i.e., to make modules as independent as


possible.
One way to measure design quality is to use coupling.

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(){
} --
}
}

 Conceptual unit can be understood easily.

8
Pattern Classification

Pattern classification is the organization of patterns into groups of patterns


sharing the same set of properties.

The GoF design patterns are classified into 3 categories.

1. Creational Patterns

2. Structural Patterns

3. Behavioral Patterns

9
Creational Patterns

 deal with object creation mechanisms.


 provide guidance on how to create objects when their creation requires
making decisions.
 encapsulate knowledge about which concrete classes the system uses.
 hide how instances of these classes are created and put together.

1. Factory Method
2. Abstract Factory
3. Builder
4. Prototype
5. Singleton

10
Creational Patterns Types

Creational patterns can be classified into two types.

1. Class Creational Patterns.


2. Object Creational Patterns.

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

Creational Structural Behavioural

Factory Method Adapter Interpreter


Abstract Factory Bridge Template Method
Builder Composite Chain of
Prototype Decorator Responsibility
Singleton Flyweight Command
Facade Iterator
Proxy Mediator
Memento
Observer
State
Strategy
Visitor

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

How to learn design patterns

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

Attach additional responsibilities to an object dynamically. Decorators


provide a flexible alternative to sub classing for extending functionality.

Sub-classing adds behavior at compile time whereas decorators provide a


new behavior at runtime.

When I inherit behavior by sub-classing, that behavior is set statically at


compile time. In addition, all subclasses must inherit the same behavior. If
however, I can extend an object’s behavior through composition, then I can do
this dynamically at runtime.

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>>

operation (): void

ConcreteComponent Decorator
Component: component

Operation (): void operation (): void

ConcreteDecorator1 ConcreteDecorator2

operation: void operation: void

23
General Implementation

Java Design Patterns suggest that Decorators should be abstract classes and
the concrete implementation should be derived from them.

Example: Christmas Tree public abstract class Decorator{


public abstract void place( Branch br);
public class ChristmasTree{ }
private Branch branch;
public Branch getBranch(){ public class BallDeco extends Decorator{
return branch; public BallDeco(ChristmasTree tree) {
} Branch br = tree.getBranch();
} place(br);
}
public void place(Branch br){
br.put(“Ball”)
}
}

StarDecorator decorator = new StarDecorator(new ChristmasTree());

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

LineNumberReader lnrd = new LineNumberReader(new FileReader (“test.csv”));


lnrd.readLine();

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

· to add responsibilities to individual objects dynamically and transparently,


that is, without affecting other objects.

· for responsibilities that can be withdrawn.

· when extension by subclassing is impractical. Or a class definition may be


hidden or otherwise unavailable for subclassing.

31
Advantages

More flexibility than inheritance.

Decorator offers a pay-as-you-go approach to adding responsibilities.

32
Disadvantages

A decorator and its component aren't identical. Thus tests for object type will fail.

Lots of little objects.

33
Composite Pattern

A Composite is an object (e.g. a shape) designed as a composition


of one-or-more similar objects, all exhibiting similar functionality.

Composite Object: Object that contain other objects.

Compose objects into tree structures to represent part-whole hierarchies.

Composite lets clients treat individual objects and compositions of objects


uniformly. This is called recursive composition.

This is known as a "has-a" relationship between objects.

34
UML Class Diagram

Component

Operation(): void
Add (Component)
getChildren()

Leaf Composite

Operation(): void Operation(): void For all g in children


Add (Component) g.operation()
getChildren()

35
General Structure of Composite Pattern

aComponent

aLeaf aLeaf aComposite aLeaf

aLeaf aLeaf aLeaf

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

public class Employee {


private String name;
private String position;
private Vector subordinates;
public Employee(String name, String position) {
setName(name);
setPosition(position);
subordinates = new Vector();
}
// write getters & setters
public void add(Employee e) {
subordinates.addElement(e);
}
public void remove(Employee e) {
subordinates.remove(e);
}
}

38
General Implementation

private void addEmployeesToTree() {


Employee ceo = new Employee(“ABC1”,”CEO”);
Employee mvp = new Employee (“MVP”, ”Marketing VP”);
Employee pvp = new Employee (“PVP” ,”Production VP”);
ceo.add(mvp);
ceo.add(pvp);
Employee smgr = new Employee (“SMGR”, ”Sales Mgr”);
Employee advMgr = new Employee (“ADVMGR” ,”Advt Mgr”);
mvp.add(smgr );
mvp.add(advMgr );
Employee sales0 = new Employee(“Sales0”,”Sales 0”);
Employee sales1 = new Employee(“Sales1”,”Sales 1”);
smgr.add(sales0);
smgr.add(sales1);
}
Vector subOrdinates = emp.getSubordinates();
if (subOrdinates.size() != 0){
getTree(subOrdinates);
}else{ System.out.println ("No Subordinates for the Employee: "+emp.getName()); }

39
JDK Implementation

JComponent

JButton JCheckBox JMenuItem JLabel

JCheckBoxMenuItem JMenu JRadioButtonMenuItem

40
Decorator Vs Composite

Composite and decorator appear to be almost identical.

A decorator enhances the behavior of a single component, whereas


a composite collects multiple components.

The intent of the decorator pattern is to enhance the behavior of a class.


The component class does not want to take the responsibility of the
decoration.

The intent of the composite pattern is to group components into a whole.

41
Composite: Applicability

Use composite when

 you want to represent part-whole hierarchies of objects.

 you want clients to be able to ignore the differences between compositions


of objects and individual objects. Clients will treat all objects in the
composite structure uniformly.

42
Advantages

It makes it easy to add new kinds of components

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

The Strategy Design Pattern basically consists of decoupling an algorithm


from its host, and encapsulating the algorithm into a separate class.

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 ()

ConcreteStrategyA ConcreteStrategyB ConcreteStrategyC

AlgorithmInterface () AlgorithmInterface () 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

public interface TaxStrategy {


public class TaxPayer { public double extortCash( TaxPayer p );
private final TaxStrategy strategy; }
private final double income;

public TaxPayer(TaxStrategy strategy, double income) {


this.strategy = strategy; this.income = income;
}

public double getIncome() {


return income;
}

public double extortCash() {


return strategy.extortCash(this);
}
}

47
General Implementation

public class CompanyTaxStrategy public class TrustTaxStrategy


implements TaxStrategy { implements TaxStrategy {
private static final double RATE = 0.30; private static final double RATE = 0.40;
public double extortCash(TaxPayer p) public double extortCash(TaxPayer p)
{ {
return p.getIncome() * RATE ; return p.getIncome() * RATE ;
} }
} }

public class EmployeeTaxStrategy


implements TaxStrategy
{
private static final double RATE = 0.45;
public double extortCash(TaxPayer p)
{
return p.getIncome() * RATE ;
}
}

48
General Implementation

public static void main(String[] args)


{

TaxPayer payer = new TaxPayer( new CompanyStrategy(),100);


TaxPayer payer2 = new TaxPayer( new TrustTaxStrategy(),100);
TaxPayer payer3 = new TaxPayer( new EmployeeTaxStrategy(),100);

System.out.println( payer.extortCash());
System.out.println( payer2.extortCash());
System.out.println( payer3.extortCash());
}

49
JDK Structure

Container LayoutManager

FlowLayout BorderLayout GridLayout

50
JDK Implementation

Panel panel = new Panel();


panel.add(new Button(“ 1 ”));
panel.add(new Button(“ 2 ”));
panel.add(new Button(“ 3 ”));
panel.add(new Button(“ 4 ”));
panel.add(new Button(“ 5 ”));
panel.add(new Button(“ 6 ”));

51
JDK Implementation - contd

Panel panel = new Panel();


panel.setLayout(new GridLayout(3, 2));
panel.add(new Button(“ 1 ”));
panel.add(new Button(“ 2 ”));
panel.add(new Button(“ 3 ”));
panel.add(new Button(“ 4 ”));
panel.add(new Button(“ 5 ”));
panel.add(new Button(“ 6 ”));

52
Applicability

Use the Strategy pattern when

 many related classes differ only in their behavior.

 a class defines many behaviors, and these appear as multiple conditional


statements in its operations. Instead of many conditionals, move related
conditional branches into their own Strategy class.

 algorithms can be selected on-the-fly at runtime.

 if you find yourself thinking that there are two or more ways of
accomplishing some task, a strategy pattern is likely needed.

53
Advantages

 A family of algorithms can be defined as a class hierarchy and can be


used interchangeably to alter application behavior without changing its
architecture.

 By encapsulating the algorithm separately, new algorithms complying with


the same interface can be easily introduced.

 Strategy enables the clients to choose the required algorithm, without


using a "switch" statement or a series of "if-else" statements.

54
Disadvantages

 Increases the number of objects

 All algorithms must use the same Strategy interface

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.

Parallel class hierarchies often require objects from one hierarchy


to be able to create appropriate objects from another.

The Factory Pattern promotes loose coupling by eliminating the need to


bind application-specific classes into the code.

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

public class IceCreamFactory {


public IceCream getIceCream(String type) {
IceCream cone = null; public class IceCreamShopV1 {
if (type.equals ("Chocolate")) { private IceCreamFactory factory;
cone = new Chocolate(); public IceCreamShopV1(IceCreamFactory factory) {
}else if (type.equals ("Strawberry")){ this.factory = factory;
cone = new Strawberry(); }
} else if (type.equals ("Vanilla")){
cone = new Vanilla(); public IceCream orderCone (String type) {
} IceCream cone; cone = factory.getIceCream(type);
return cone; cone.scoop();
} return cone;
} }

public static void main(String[] args) {


IceCreamFactory factory = new IceCreamFactory();
IceCreamShopV1 shop = new IceCreamShopV1(factory);
Benefit: Decoupling shop.orderCone ("Chocolate");
}
}

59
JDK Implementation

Border blackline = BorderFactory.createLineBorder(Color.black);

Border b2 = BorderFactory.createEtchedBorder(EtchedBorder.RAISED);

Border raisedbevel = BorderFactory.createRaisedBevelBorder();

60
JDK Implementation – cont’d

Factory Method in JDK:

java.util.Calendar.getInstance();

61
Advantages

 Eliminates the need to bind application-specific classes into your code.

 Provides hooks for subclassing. Creating objects inside a class with a


factory method is always more flexible than creating an object directly.

 Connects parallel hierarchies. Factory method localizes knowledge of which


classes belong together. Parallel class hierarchies result when a class
delegates some of its responsibilities to a separate class.

62
Disadvantages

 Clients might have to subclass the Creator class just to


create a particular Concrete object.

63
Iterator Pattern

Provide a way to access the elements of an aggregate object sequentially


without exposing its underlying representation.

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.

Examples are a linked list and a hash table.

64
Structure

Client Iterator
Aggregate
First()
CreateIterator()
Next()
IsDone()
CurrentItem()

ConcreteAggregate ConcreteIterator

CreateIterator()

Return new concrete iterator (this)

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

 We could implement the Iterator pattern “from scratch” in Java.


 The java.util.Enumeration interface acts as the Iterator interface.
 Aggregate classes that want to support iteration provide methods that
return a reference to an Enumeration object.
 This Enumeration object implements the Enumeration interface and
allows a client to traverse the aggregate object.
 Java JDK 1.1 has a limited number of aggregate classes: Vector and
Hashtable.

 Java JDK 1.2 introduced a new Collections package with more


aggregate classes, including sets, lists, maps and an Iterator interface..

67
The Enumeration Interface

public abstract boolean hasMoreElements()


Returns true if this enumeration contains more elements; false otherwise.

public abstract Object nextElement()


Returns the next element of this enumeration.
Throws: NoSuchElementException if no more elements exist.

Correspondences:

hasMoreElements() => IsDone()

nextElement() => Next() followed by CurrentItem()

Note that there is no First(). First() is done automatically when the


Enumeration is created.

68
Applicability

Use the Iterator pattern:


 To support traversals of aggregate objects without exposing their
internal representation.

 To support multiple, concurrent traversals of aggregate objects.

 To provide a uniform interface for traversing different aggregate


structures (that is, to support polymorphic iteration)

69
Consequences

Benefits

 Simplifies the interface of the Aggregate by not polluting it with


traversal methods.
 Supports multiple, concurrent traversals.
 Supports variant traversal techniques.

Liabilities

None!

70
Observer Pattern

Define a one-to-many dependency between objects so that when one object


changes state, all its dependents are notified and updated automatically.

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.

This kind of interaction is also known as publish-subscribe. The subject is


the publisher of notifications. It sends out these notifications without having to
Know who its observers are. Any number of observers can subscribe to
receive notifications.

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

There are two ways to look at the Observer pattern.

1. Observer Interface and Observable class found in the java.util


package.

2. The JavaBeans component model of registering event listeners with


components.

75
Issue with Observable pattern

You have to extend Observable class.


 might not be possible in the single-inheritance world of the Java platform

76
JavaBeans component model

Registering event listeners involves a series of add and remove methods,


where the listener type is embedded in the method name.

To observe the selection of a button, you register an ActionListener with


the component:
ActionListener listener = new ActionListener()
{
public void actionPerformed(ActionEvent actionEvent)
{
...
}
};
JButton button = new JButton("Pick Me");
button.addActionListener(listener);

77
Advantages of Observer Pattern

Enable the loose coupling of the Subject and Observer.

Java Message Service (JMS), with its guaranteed delivery, non-local distribution,
and persistence.

Support for broadcast communication.

78
Complications to watch with Observer Pattern

 Possibility of a memory leak. Until the Subject releases the reference,


the Observer cannot be removed by the garbage collector.

 Set of Observer objects is maintained in an unordered collection

 You must introduce an intermediary object to enforce the ordering.

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

In order to implement Singleton pattern,


1. create private constructor.
2. create a private static variable which hold the instance for
the singleton class.
3. create a public static method which returns the singleton
instance.

Now you can easily create a singleton instance by simply invoking


the static method.

82
General Implementation

public final class Test{


public final class CsvReader{
public static void main (String args []){
private CsvReader(){ CsvReader reader = CsvReader.getCsvReader();
} reader.importData(“C:/Test.csv”,”UTF-8”, true);
}
public static CsvReader reader=null; }

public static synchronized getCsvReader(){


if( reader==null){
reader = new CsvReader();
}
}
}

83
JDK Implementation

Runtime rt = Runtime.getRuntime();

Connection con = java.sql.DriverManager. getConnection()

ToolTipManager tm = javax.swing.ToolTipManager. sharedInstance()

SecurityManager manager = System.getSecurityManager()


Toolkit kit = Toolkit.getDefaultToolkit()

84
Points to ponder

1. Singleton instance is only created only when needed. This is called


lazy instantiation.
Example:
Class Singleton{
private static Singleton uniqueInstance =null;
public static Singleton getInstance() {
if(uniqueInstance!=null) {
uniqueInstance = new Singleton();
}
}
If two threads concurrently invoke the static method, then it may create two
instances for the singleton class. This can be avoid by making instance method
as synchronized. The other approach could be do eager instantiation.
private static Singleton uniqueInstance = new Singleton();

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.

Singleton obj = Singleton.getInstance()

Singleton clonedObject = (Singleton ) obj.clone();

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.

public Object clone() throws CloneNotSupportedException {


throw new CloneNotSupportedException();
}

86
Thread-safe implementation

The above implementation was both lazy and non-thread safe.

Two threads trying to create an instance.


public static Singleton CreateInstance()
{
// Use a mutex locking mechanism that suits your system
LockCriticalSection();
if (instance == null)
{
instance = new Singleton();
}
UnLockCriticalSection();
return instance;
}

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.

The ‘clever’ double locking system ‘tries’ to fix this problem.

88
Double-checked Locking implementation

if( instance == null) //first check


{
// Use a mutex locking mechanism that suits your system
LockCriticalSection();
if (instance == null) //second check
{
instance = new Singleton();
}
UnLockCriticalSection();
}
return instance;

89
Issues with Singleton

“Singleton" is very common and the common implementation is using


a static reference.”
- But it leaves floating garbage that is not in use.
Example:
A singleton is only a singleton to the classloader it lives in. A webapp is loaded
in its own classloader, so when it is start/stopped or reloaded - a new
classloader is made. And so is a brand new set of singletons.
So the alternative is “WeakSingleton”
- when all other references to the original instance have expired
the instance is cleaned.

implement using java.lang.ref.WeakReference

90
Implementing WeakSingleton

public class WeakSingleton{


private static WeakReference<WeakSingleton> weakReference;
private WeakSingleton(){ }
public static synchronized WeakSingleton getInstance(){
WeakSingleton result;
if (weakReference ==null) {
result = new WeakSingleton();
weakReference = new WeakReference<WeakSingleton>(result);
} else {
result = weakReference.get();
if (result==null) {
result = new WeakSingleton();
weakReference = new WeakReference<WeakSingleton>(result);
}
}
return result;
}
protected void finalize() {
System.out.println ("Weak singleton will be GC'ed");
}

91
Implementation Issues

Singleton is a commonly (mis) used design pattern.

Users of this pattern should be aware of the scope & lifecycle control of the
singleton object.

Singleton could be at various scope levels.

1. Singleton object within a operating system environment or JVM.


2. Singleton object across clustered environments.
- It may not be considered singleton from application's perspective.

3. Singleton in a multi-threaded application.


- It should be thread safe for which programming Idioms are available.

92
Advantages of Singleton Pattern

Controlled access to sole instance.


Reduced name space.
Permits a variable number of instances.
More flexible than class operations.

93
Disadvantages of Singleton Pattern

Overhead involved in checking whether an instance of the class already exists


every time an object requests a reference. This problem can be overcome by
using static initialization.

Object lifetime. Singleton does not address the issue of deleting the single object.

Reuse and testability.


increased opacity of the class making it harder to unit test with mock objects.

94
Prototype Pattern

Specify the kinds of objects to create using a prototypical instance, and


create new objects by copying this prototype.
The prototype means making a clone. This implies cloning of an object
to avoid creation.

95
Structure

Client Prototype
getInstance( ) Clone()

ConcretePrototype1 ConcretePrototype2

Clone() Clone()

96
UML Diagram

Client Prototype

Create Compatible Copy of Prototype

Copy Data

Return ()

97
General Implementation

public interface CloneableAnimal


extends Cloneable {
public CloneableAnimal duplicate( );
} public class Sheep implements CloneableAnimal {
public Sheep( ) {
System.out.println( "Sheep template created" );
}
public CloneableAnimal duplicate( ) {
System.out.println( "the Sheep will clone itself" );
Sheep returnValue = null;
try {
returnValue = ( Sheep ) super.clone( );
} catch( Exception e ) {
System.out.println( "error cloning Sheep" );
}
return returnValue;
}
}

98
General Implementation

public class Cow implements public class CloningMachine{


CloneableAnimal{ public CloningMachine( ) {
public Cow( ) { }
System.out.println( "Cow template created" ); public CloneableAnimal newClone(
} CloneableAnimal template ){
public CloneableAnimal duplicate( ) { return template.duplicate( );
System.out.println( "creating a new }
Cow instance" );
return new Cow( ); public CloneableAnimal[] cloneMany( int itemCount,
} CloneableAnimal template ) {
public String toString( ) { CloneableAnimal[] returnValue = new CloneableAnimal
return "Muuuu, cow clone" ; [itemCount ];
} for( int i=0; i< itemCount; i++ ) {
} returnValue[ i ] = template.duplicate( );
}
return returnValue;
}
}

99
General Implementation

public class Test {


public static void main( String[] args ) {
CloningMachine cMachine = new CloningMachine( );
Sheep sheepTemplate = new Sheep( );
Cow cowTemplate = new Cow( );
Cow clonedCow = ( Cow ) cMachine.newClone( cowTemplate );
Sheep clonedSheep = ( Sheep ) cMachine.newClone( sheepTemplate );

sayIt( "first cloned sheep" );


System.out.println( clonedSheep );

CloneableAnimal[] newCows = cMachine.cloneMany( 10, cowTemplate );


sayIt( "Creating 10 new Sheeps" );

CloneableAnimal[] newSheeps = cMachine.cloneMany( 10, sheepTemplate );


}
}

100
JDK Implementation

Implemented through Java.lang.Cloneable and Object.clone() method.

101
Using clone()

The default behavior of clone() performs a shallow copy, but subclasses


often change this to perform a deep copy.

102
Applicability

When the classes to instantiate are specified at run-time,


for example, by dynamic loading;
To avoid building a class hierarchy of factories that parallels the class
hierarchy of products;
when instances of a class can have one of only a few different
combinations of state.

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

Command pattern is a design pattern in which objects are used to represent


actions. A command object encapsulates an action and its parameters.

The Chain of Responsibility forwards requests along a chain of classes, but


the Command pattern forwards a request only to a specific module.

It encloses a request for a specific action inside an object and gives it a


known public interface.

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.

 When a user selects one of these controls, the program receives an


ActionEvent, which it must trap by sub classing, the actionPerformed event.

 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.

 It also contains one button called btnRed.


 A click on any of these causes an actionPerformed event that we can trap.

109
JDK Implementation cont’d

public void actionPerformed (ActionEvent e){


Object obj = e.getSource();
if (obj == mnuOpen) fileOpen();
if (obj == mnuExit) exitClicked();
if (obj == btnRed) redClicked();
}

private void fileOpen(){


FileDialog fdlg = new FileDialog(this, ”Open”, FileDialog.LOAD)}
private void exitClicked() {
System.exit(0);}

private void redClicked() {


p.setBackGround (Color.RED);
}

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..

The objective is to reduce the actionPerformed method to:

Public void actionPerformed(ActionEvent e){


Command cmd = (Command) e.getSource();
cmd.execute();
}

112
The Command Object

 One way to assure that every object receives its own commands directly is to

use the Command object approach.


 A Command object always has an Execute() method that is called when an
action occurs on that object.
 Most simply, a Command object implements at least the following interface.
public interface Command
{
public void execute();
}

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

To implement this approach, we create little classes each of which implements


the ActionListener interface:
class BtnRed implements ActionListener {
public void actionPerformed(ActionEvent e) { p.setBackground(Color.red);
}
}

class FileExit implements ActionListener {


public void actionPerformed(ActionEvent e) { System.exit(0); }
}

and register them as listeners in the usual way.


mnuOpen.addActionListener(new FileOpen());
mnuExit.addActionListener(new FileExit());
btnRed.addActionListener(new BtnRed());

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

The Command pattern has the following consequences:

1. Command decouples the object that invokes the operation from the one
that knows how to perform it.

2. Commands are first-class objects. They can be manipulated and extended


like any other object.

3. You can assemble commands into a composite command.

4. It's easy to add new Commands, because you don't have to change
existing classes.

116
Disadvantage of Command Pattern

 it tends to lead to a proliferation of small classes.

117
Adapter Pattern
Two-prong wall outlet three-prong plug

Adapter is about creating an intermediary abstraction that translates, or maps,


the old component to the new system. Clients call methods on the Adapter object
which redirects them into calls to the legacy component. Or
The Adapter Pattern converts one interface into another so that two classes can
work together without having to change their code.
This strategy can be implemented either with inheritance or with aggregation.
Adapter functions as a wrapper or modifier of an existing class. It provides a
different or translated view of that class.

118
Applicability

Convert the interface of a class into another interface clients expect.

Use the Adapter pattern when


 you want to use an existing class, and its interface does not match
the one you need.
 you want to create a reusable class that cooperates with unrelated
or unforeseen classes, that is, classes that don't necessarily have
compatible interfaces.

 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

Client Target Adaptee


Request() SpecificRequest()

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:

Clients call operations on an Adapter instance. In turn, the


adapter calls Adaptee operations that carry out the request.

121
Implementation

There are two ways to do this: by inheritance, and by object composition.

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

Adapter has two form:


1. Class Adapter.
 Uses multiple inheritance to achieve its goal.
 The adapter is created inheriting interfaces from both the interface that is
expected and the interface that is pre-existing.
 Class Adapter pattern less frequently used in languages such as Java

2. Object Adapter

 The adapter contains an instance of the class it wraps.


 In this situation, the adapter makes calls to the instance of the wrapped
object.

123
Class Adapter

Adaptee1 AdapteeN

+method1() +methodN()

Client Adapter
+adapter Adapter

doWork() methodA()

Method1()
adapter.methodA() .
.
methodN()

124
Object Adapter

Adaptee

+methodB()

Client Adapter

+adapter Adapter +adaptee Adaptee

doWork() +methodA()

adapter.methodA() adaptee.methodB()

125
Class Adapter Vs Object Adapter

The Class 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.

The Object adapter


 Could allow subclasses to be adapted by simply passing them in as part
of a constructor.
 Requires that you specifically bring any of the adapted object’s methods
to the surface that you wish to make available.

126
Two Way Adapters

Allows an object to be viewed by different classes as being either of type.

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

DoublePin TriplePin public static void main(String args[])


{
TriplePin triple = new TriplePin();
insertDouble() insertTriple() DoublePin double = new DoublePin();
double.insert Double();
}
Adapter
Adapter adapter = new Adapter(roundPeg);
triple TriplePin
adapter.insert Double ();
insertDouble ()

triple.insertTriple();

The Adapter class adapts a TriplePin to DoublePin. The interface for


Adapter is DoublePin.

128
Implementing Two Way Adapters

public interface IDoublePin(){ public interface ITriplePin(){


insertDouble(); insertTriple();
} }

public class DoublePin() public class TriplePin()


implements IDoublePin implements ITriplePin {
{ insertTriple();
insertDouble(); }
public class Client () {
}
public static void main(String args[]){
public class Adapter () implements
DoublePin dp = new DoublePin();
IDoublePin, ITriplePin {
TriplePin tp = new TriplePin();
private DoublePin dp;
dp.insertDouble(); //One-way Adapter
private TriplePin tp;
IDoublePin dToT = new Adapter(tp);
public Adapter (DoublePin dp){ this.dp
dToT.insertDouble();
=dp }
ITriplePin tToD = new Adapter(dp);
public Adapter (TriplePin tp){ this.tp =tp }
tToD.insertTriple();
public void insertDouble(){ tp.insertTriple() }
}
public void insertTriple()
}
{ dp.insertDouble() }
}
129
Pluggable Adapters

Adapts dynamically to one of several classes.


A class is more reusable when you minimize the assumptions other classes
must make to use it.

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.

The following are some of the Adapter Classes in JDK


 ComponentAdapter
 ContainerAdapter
 FocusAdapter
 KeyAdapter
 MouseAdapter
 MouseMotionAdapter

131
Advantages

 Allow desperate objects to work together.

 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

Complex Object Proxy for Bank

135
Proxy Pattern

Applicability

Proxies are useful wherever there is a need for a more sophisticated


reference to a object than a simple pointer or simple reference can provide

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.

4. Smart Reference Proxy


- is a replacement for a bare pointer.
- counting the number of references to the real object so that it can be
freed automatically when there are no more references.
- loading a persistent object into memory when it's first referenced.
- checking that the real object is locked before it's accessed to ensure
that no other object can change it.

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

JDK implemented proxy pattern through java.lang.reflect package


 The following are the classes & interfaces:
1. java.lang.reflect.Proxy (c)
2. java.lang.reflect.InvocationHandler (i)

 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

Vehicle with non-proxy


Public interface IVehicle{
public void start();
Start public void stop();
forward public void forward();
Client public void reverse();
Stop
public String getName();
}

public class Car implements IVehicle {


private String name; public class Client {
public Car(String name) {this.name = name;} public static void main(String[] args) {
public void start() { IVehicle v = new Car (“Indica");
System.out.println ("Car " + name + " started"); v.start();
} v.forward();
// stop(), forward(), reverse() implemented similarly. v.stop();
// getName() not shown. }
} }

142
Example Cont’d

Vehicle with Proxy

Start Start
forward forward
Client Proxy
Stop Stop

public class VehicleProxy implements IVehicle { public class Client {


private IVehicle v; public static void main(String[] args) {
public VehicleProxy (IVehicle v) {this.v = v;} IVehicle c = new Car("Botar");
public void start() { IVehicle v = new VehicleProxy(c);
System.out.println ("VehicleProxy: Begin of v.start();
start()"); v.forward();
v.start(); v.stop();
System.out.println ("VehicleProxy: End of start()"); }
} }
// stop(), forward(), reverse() implemented similarly.
// getName() not shown.
}

143
Applicability

Proxy is applicable whenever there is a need for a more versatile or sophisticated


reference to an object than a simple pointer.

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

The Proxy pattern introduces a level of indirection when accessing an object.


The additional indirection has many uses, depending on the kind of proxy:

1. A remote proxy can hide the fact that an object resides in a different
address space.

2. A virtual proxy can perform optimizations such as creating an object on


demand.
3. Both protection proxies and smart references allow additional housekeeping
tasks when an object is accessed.

Adapter provides a different interface to its subject.


Proxy provides the same interface.
Decorator provides an enhanced interface.

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

You might also like