51
8/3/2019 prutt05_lec5 http://slidepdf.com/reader/full/prutt05lec5 1/51 5. Design Patterns Are the answer to a question that commonly arises “  How can I … ?” Patterns record successful solutions in software development for sharing between projects. Gang of Four (GoF) Gamma, Helm, Johnson, Vlissides, - founders of movement. Gamma et al, Design Patterns: Elements of  Reusable Object-Oriented Software , Addison Wesley, 1995.

prutt05_lec5

Embed Size (px)

Citation preview

Page 1: prutt05_lec5

8/3/2019 prutt05_lec5

http://slidepdf.com/reader/full/prutt05lec5 1/51

5. Design Patterns

• Are the answer to a question that commonly

arises “ How can I … ?” 

• Patterns record successful solutions in softwaredevelopment for sharing between projects.

• Gang of Four (GoF) Gamma, Helm, Johnson,Vlissides, - founders of movement.

• Gamma et al, Design Patterns: Elements of  Reusable Object-Oriented Software, AddisonWesley, 1995.

Page 2: prutt05_lec5

8/3/2019 prutt05_lec5

http://slidepdf.com/reader/full/prutt05lec5 2/51

Patterns solve software structural problems

like:

• Abstraction,

• Encapsulation

• Information hiding

• Separation of concerns

• Coupling and cohesion

• Separation of interface and implementation

• Single point of reference

• Divide and conquer 

Page 3: prutt05_lec5

8/3/2019 prutt05_lec5

http://slidepdf.com/reader/full/prutt05lec5 3/51

Patterns also solve non-functional problems

like:

• Changeability

• Interoperability

• Efficiency• Reliability

• Testability

• Reusability

Page 4: prutt05_lec5

8/3/2019 prutt05_lec5

http://slidepdf.com/reader/full/prutt05lec5 4/51

5.1. Types of Pattern

There are 3 types of pattern … – Creational: address problems of creating an

object in a flexible way. Separate creation, fromoperation/use.

 – Structural: address problems of using O-Oconstructs like inheritance to organize classes andobjects

 – Behavioral: address problems of assigningresponsibilities to classes. Suggest both staticrelationships and patterns of communication

(use cases)

Page 5: prutt05_lec5

8/3/2019 prutt05_lec5

http://slidepdf.com/reader/full/prutt05lec5 5/51

5.2. Patterns, Architectures &

Frameworks• There can be confusion between patterns,

architectures and frameworks.

• Let’s try to distinguish them:• Architectures model software structure at

the highest possible level, and give the

overall system view. An architecture canuse many different patterns in differentcomponents

Page 6: prutt05_lec5

8/3/2019 prutt05_lec5

http://slidepdf.com/reader/full/prutt05lec5 6/51

• Patterns are more like small-scale or local

architectures for architectural componentsor sub-components

• Frameworks are partially completed

software systems that may be targeted at a

 particular type of application. These are

tailored by completing the unfinished

components.

Page 7: prutt05_lec5

8/3/2019 prutt05_lec5

http://slidepdf.com/reader/full/prutt05lec5 7/51

Summary of Differences

• Patterns are more general and abstract thanframeworks. A pattern is a description of a

solution, not a solution itself.• A pattern cannot be directly implemented.

An implementation is an example of a pattern.

• Patterns are more primitive thanframeworks. A framework can employseveral patterns.

Page 8: prutt05_lec5

8/3/2019 prutt05_lec5

http://slidepdf.com/reader/full/prutt05lec5 8/51

5.3 Catalogues & Languages

• Patterns are grouped into catalogues and

languages

• A catalogue is group of patterns that may

 be reasonable to use together 

• A language is a more closely related

collection useful for a common problemdomain, e.g. Banking.

Page 9: prutt05_lec5

8/3/2019 prutt05_lec5

http://slidepdf.com/reader/full/prutt05lec5 9/51

5.4 Pattern Templates

• Different authors use different templates to

describe their patterns

• Information is not always presented in the

same way.

• Consult your manual/source !!!

• A typical template would be …

Page 10: prutt05_lec5

8/3/2019 prutt05_lec5

http://slidepdf.com/reader/full/prutt05lec5 10/51

• Name: meaningful text that reflects the problem,

e.g. Bridge, Mediator, Flyweight

• Problem addressed: intent of the pattern,objectives achieved within certain constraints

• Context: circumstances under which it can occur,

used to determine applicability•  Forces: constraints or issues that solution must

address, forces may conflict!

• Solution: the static and dynamic relationships

among the pattern components. Structure, participants, collaboration. Solution must resolve

all forces!

Page 11: prutt05_lec5

8/3/2019 prutt05_lec5

http://slidepdf.com/reader/full/prutt05lec5 11/51

5.5. Pattern: Singleton

(Creational)Name: Singleton

Problem: 

How can we guarantee that one and only one

instance of a class can be created?

Context: In some applications it is important

to have exactly one instance of a class, e.g. sales of one company.

Page 12: prutt05_lec5

8/3/2019 prutt05_lec5

http://slidepdf.com/reader/full/prutt05lec5 12/51

Forces: Can make an object globally accessible as a

global variable, but this violates encapsulation.

Could use class (static) operations and attributes, but

 polymorphic redefinition is not always possible.

Solution:Create a class with a class operation getInstance().

When class is first accessed, this creates relevant

object instance and returns object identity to client.

On subsequent calls of getInstance(), no new

instance is created, but identity of existing object is

returned.

Page 13: prutt05_lec5

8/3/2019 prutt05_lec5

http://slidepdf.com/reader/full/prutt05lec5 13/51

Singleton Structure

Singleton

-uniqueInstance

-singletonData

+getInstance( )

+getSingletonData( )

+singletonOperation( )

-Singleton( )

Object identifier for singletoninstance, class scope or static

Returns object identifier for 

unique instance, class-scope

or static

Private constructor only accessible

via getInstance()

getInstance( ) {

if ( uniqueInstance == null )

{ uniqueInstance = new Singleton( ) }

return uniqueInstance

}

Page 14: prutt05_lec5

8/3/2019 prutt05_lec5

http://slidepdf.com/reader/full/prutt05lec5 14/51

Class Singleton {

private static Singleton uniqueInstance = null;

private Singleton( ) { .. } // private constructor 

public static Singleton getInstance( ) {

if (uniqueInstance == null)

uniqueInstance = new Singleton();

 // call constructor 

return uniqueInstance;

}

}

Example: Code

Page 15: prutt05_lec5

8/3/2019 prutt05_lec5

http://slidepdf.com/reader/full/prutt05lec5 15/51

Comments

• To specify a class has only one instance, we make

it inherit from Singleton.

+ controlled access to single object instance through

Singleton encapsulation

+ Can tailor for any finite number of instances

+ namespace not extended by global variables

- access requires additional message passing- Pattern limits flexibility, significant redesign if 

singleton class later gets many instances

Page 16: prutt05_lec5

8/3/2019 prutt05_lec5

http://slidepdf.com/reader/full/prutt05lec5 16/51

5.6. Pattern: Façade

(Structural)Name: Façade

Problem: 

How can we access a large number of classes

with a complex internal interaction in a simple

 but safe way?

Solution: Introduce a dedicated interface classthat simplifies the view of the class collection.

Page 17: prutt05_lec5

8/3/2019 prutt05_lec5

http://slidepdf.com/reader/full/prutt05lec5 17/51

Facade Structure

Facadesubsystem classes

Page 18: prutt05_lec5

8/3/2019 prutt05_lec5

http://slidepdf.com/reader/full/prutt05lec5 18/51

<<façade>>

SecurityManager 

+addAccessRight()

+addActor()

+addActorRole()

+removeActor()

AccessRight

+addAccessRight()

Actor 

+addActor()

+removeActor()

+changeSalary()

ActorRole

+addActorRole()

Method not in Facade

Pattern Name

Page 19: prutt05_lec5

8/3/2019 prutt05_lec5

http://slidepdf.com/reader/full/prutt05lec5 19/51

Comments

• Clients communicate with the subsystem bysending requests to Façade which forwards

them to the appropriate subsystem object(s).• Although subsystem objects perform actual

work, Façade may have to translate itsinterface to subsystem interfaces.

• Clients that use the Façade don’t have toaccess its subsystem objects directly.

Page 20: prutt05_lec5

8/3/2019 prutt05_lec5

http://slidepdf.com/reader/full/prutt05lec5 20/51

• Usually only one Façade object isrequired. Thus a Façade object is often asingleton.

• Factory pattern can be used with Façade to provide an interface for creating

subsystem objects in a subsystemindependent way.

• Factory can also be used as an alternative

to Façade to hide platform-specific classes.• Mediator pattern is similar to Façade inabstracting functionality of classes.

Page 21: prutt05_lec5

8/3/2019 prutt05_lec5

http://slidepdf.com/reader/full/prutt05lec5 21/51

5.7. Pattern: Mediator

(Behavioral)

Problem:

How can we deal with two or more classes

which sometimes interact, but can also be usedseparately?

Solution: Mediator promotes loose coupling

 by keeping objects from referring to one another 

explicitly. Put each interaction between objects

in a separate (Mediator ) class. This class

should have references to the objects.

Page 22: prutt05_lec5

8/3/2019 prutt05_lec5

http://slidepdf.com/reader/full/prutt05lec5 22/51

• A pattern for two objects which exist

independently but have some coupling. This

coupling is placed in its own class.• Used by e.g. ActionListener in graphics

which couples together two graphical

objects, e.g. window & button

Page 23: prutt05_lec5

8/3/2019 prutt05_lec5

http://slidepdf.com/reader/full/prutt05lec5 23/51

Mediator Structure

Mediator 

ConcreteMediator 

mediator 1

*

*

Colleague

Concrete

Colleague1

Concrete

Colleague2

Page 24: prutt05_lec5

8/3/2019 prutt05_lec5

http://slidepdf.com/reader/full/prutt05lec5 24/51

• Colleagues send and receive requests from a

Mediator object. The mediator implements

the cooperative behavior by routingrequests between appropriate colleagues.

Page 25: prutt05_lec5

8/3/2019 prutt05_lec5

http://slidepdf.com/reader/full/prutt05lec5 25/51

Example: Top-Down Design

Mediator 

File_Selector 

mediator 1

*

*

Colleague

Browser Text_Field

My_Application

Button*

Page 26: prutt05_lec5

8/3/2019 prutt05_lec5

http://slidepdf.com/reader/full/prutt05lec5 26/51

Comments

• Façade, unlike Mediator , abstracts a

subsystem of objects to provide a

convenient interface. Unidirectional.Façade objects make requests of the

subsystem, but not vice-versa.

• Mediator enables cooperative behaviour,that colleagues don’t or can’t provide.

Multidirectional.

Page 27: prutt05_lec5

8/3/2019 prutt05_lec5

http://slidepdf.com/reader/full/prutt05lec5 27/51

• Observer pattern and Mediator both

receive notification of changes.

• Observer does so through an abstractmechanism. Allows source of notification to

 be independent of its observers.

• In Mediator , the source must know itsmediator. This makes it possible for 

mediator to define reactions to each

stimulus.

Page 28: prutt05_lec5

8/3/2019 prutt05_lec5

http://slidepdf.com/reader/full/prutt05lec5 28/51

5.8. Pattern: Observer

(Behavioral)Name: Observer 

Problem: Define a one-to-many dependency

among objects so that when one object

changes state, all of its dependents are

notified and updated automatically.Solution: MVC, but refined by separating

abstract from concrete subjects and observers

Page 29: prutt05_lec5

8/3/2019 prutt05_lec5

http://slidepdf.com/reader/full/prutt05lec5 29/51

Observer 

ConcreteObserver 

Update()

observerState

update()

Subject

ConcreteSubject

attach(Observer)

detach(Observer)

notify()

subjectState()getState()

setState()

*

*

observerState =

subject.getState( )

return

subjectState

for all o in

observers {o.update( ) }

Page 30: prutt05_lec5

8/3/2019 prutt05_lec5

http://slidepdf.com/reader/full/prutt05lec5 30/51

• ConcreteSubject notifies its observerswhenever a change occurs that could make

its observers state inconsistent with its own• After being informed of change, aConcreteObserver queries the subject toreconcile its state with subjects.

• Observer object that initiates changerequest postpones its update until it getsnotification from subject. Notify() is not

always called by subject. Can be called byan observer, or any other object.

• Pattern is well known, has wide range of variants

Page 31: prutt05_lec5

8/3/2019 prutt05_lec5

http://slidepdf.com/reader/full/prutt05lec5 31/51

aConcrete

Subject:

aConcrete

Subject:

aConcrete

Subject:

setState( )

notify( )

update( )

getState( )

update( )

getState( )

Page 32: prutt05_lec5

8/3/2019 prutt05_lec5

http://slidepdf.com/reader/full/prutt05lec5 32/51

5.9. Pattern: Mock Object

• A pattern where coupling an objectscoupling to another complex object is

replaced by coupling to a simplified proxy.• C.f. dummy methods in whishful thinking

• Coupling between objects could well be aninterface. Then the mock and real objectsimplement this interface.

• Used e.g. in testing objects. (see Section 8)

Page 33: prutt05_lec5

8/3/2019 prutt05_lec5

http://slidepdf.com/reader/full/prutt05lec5 33/51

5.10 Pattern: Factory

Name: (Abstract) Factory

Problem: Provide an interface for creating

families of related or dependent objects

without specifying their concrete classes.

• Control instantiation

• Singleton is a special case of Factory whereonly one object can be created.

Page 34: prutt05_lec5

8/3/2019 prutt05_lec5

http://slidepdf.com/reader/full/prutt05lec5 34/51

Factory Structure

 AbstractProduct

ConcreteProduct1

 AbstractFactory

ConcreteFactory

FactoryMethod()

 AnOperation()

FactoryMethod()

Product =

FactoryMethod()

return new

ConcreteProduct()

Page 35: prutt05_lec5

8/3/2019 prutt05_lec5

http://slidepdf.com/reader/full/prutt05lec5 35/51

•  Normally, a single instance of a

ConcreteFactory class is created atruntime.

• This creates product objects having a

 particular implementation.• To create different product objects, clients

should use a different concrete factory.

• AbstractFactory defers creation of productobjects to its ConcreteFactory subclasses.

Factory Class Model

Page 36: prutt05_lec5

8/3/2019 prutt05_lec5

http://slidepdf.com/reader/full/prutt05lec5 36/51

MyClass

createObjectOfRequiredClass():RequiredClass

Factory design pattern

Client RequiredClass

Factory Class Model

create objects

Page 37: prutt05_lec5

8/3/2019 prutt05_lec5

http://slidepdf.com/reader/full/prutt05lec5 37/51

5.10.1 Factory Example

• E.g. create objects of different types

• We can order a Car and get an

Aston Martin, MG, Jaguar etc

• We don’t know which factory builds the

car, just that they implement CarFactory.

Owner has created the actual factory

instance.

Page 38: prutt05_lec5

8/3/2019 prutt05_lec5

http://slidepdf.com/reader/full/prutt05lec5 38/51

// we have a reference to owner 

CarFactory aFactory = owner.makefactory();

Car myCar =aFactory.makeCar(“AstonMartin”);

class BritishFactory implements CarFactory{

public Car makeCar(String b) throwsException {

if(b.equals(“AstonMartin”)) return new AstonMartin();

else if (..) return ..;else throw new Exception(b + “doesn’t

exist”);

}

}

Page 39: prutt05_lec5

8/3/2019 prutt05_lec5

http://slidepdf.com/reader/full/prutt05lec5 39/51

Class AstonMartin extends Car {}

Class Jaguar extends Car {}

Interface CarFactory {

Public Car makeCar(String b) throws Exception;

}

Page 40: prutt05_lec5

8/3/2019 prutt05_lec5

http://slidepdf.com/reader/full/prutt05lec5 40/51

• Abstract Factory classes are often

implemented with the Factory Method 

 pattern.• Can also be implemented using the

Prototype pattern.

• A concrete factory is often a Singleton.

Comments

Page 41: prutt05_lec5

8/3/2019 prutt05_lec5

http://slidepdf.com/reader/full/prutt05lec5 41/51

5.11 Command

Name: Command

Problem: Need a flexible organization for 

methods that allows them to be context

sensitive in a structured way.

Solution: Place behaviour /operation in an

own class instead of in a method.

Page 42: prutt05_lec5

8/3/2019 prutt05_lec5

http://slidepdf.com/reader/full/prutt05lec5 42/51

Examples

• Undo. It’s difficult to undo effects of an

arbitrary method. Methods vary over time.

• Choose menu option. Whether an option

can be chosen at any time depends on many

factors.

Page 43: prutt05_lec5

8/3/2019 prutt05_lec5

http://slidepdf.com/reader/full/prutt05lec5 43/51

Command Structure

Command

ConcreteCommand

Execute()

Execute()

State

Receiver.Action()

Invoker Client1

Receiver 

 Action()

1 receiver 

Page 44: prutt05_lec5

8/3/2019 prutt05_lec5

http://slidepdf.com/reader/full/prutt05lec5 44/51

• Client creates a ConcreteCommand object

and specifies its receiver.

• An Invoker object stores the

ConcreteCommand object

• The invoker issues a request by calling

Execute on the command. When commands

are undoable, ConcreteCommand stores

state for undoing the command before

invoking Execute• ConcreteCommand object invokes

operations on its receiver to carry out request

Page 45: prutt05_lec5

8/3/2019 prutt05_lec5

http://slidepdf.com/reader/full/prutt05lec5 45/51

aClient aCommand anInvoker aReceiver  

new Command(aReceiver)

Execute()

storeCommand(aCommand)

Action()

Page 46: prutt05_lec5

8/3/2019 prutt05_lec5

http://slidepdf.com/reader/full/prutt05lec5 46/51

Comments

• Pattern replaces function pointers ( passing 

 functions as parameters) which is not

available in some languages.• Pattern allows a class to call a receivers

routine without knowledge of it. Gives high

degree of decoupling between caller andcallee.

Page 47: prutt05_lec5

8/3/2019 prutt05_lec5

http://slidepdf.com/reader/full/prutt05lec5 47/51

Command (Cont.)

• Client:

Command command =

Command.getCommand (…);• Command.execute();

• A Factory method first gives a Command

object (means object can depend on currentsituation)

• Then call execution command execute()

Page 48: prutt05_lec5

8/3/2019 prutt05_lec5

http://slidepdf.com/reader/full/prutt05lec5 48/51

class Command {

public void execute() {

if (check-something) { //menu itemselectable?

this.getParameters(); //preparation

getTarget1().action1(); //do something

}

else

// do something else,

// like other action or target}

}

Page 49: prutt05_lec5

8/3/2019 prutt05_lec5

http://slidepdf.com/reader/full/prutt05lec5 49/51

Related Patterns

• A Memento pattern can be used the keep

the state a command needs to undo its

effect.• A command that must be copied before

 being placed on the history list acts as a

Prototype pattern.

Page 50: prutt05_lec5

8/3/2019 prutt05_lec5

http://slidepdf.com/reader/full/prutt05lec5 50/51

Guidelines Checklist

• Is there a pattern that addresses my problem?

• Does the pattern provide an acceptable solution?

• Is there a simpler solution? (pattern overuse)• Is the context of the pattern consistent with my

 problem?

• Are the consequences of using the pattern

acceptable?• Are there forces in my environment that conflict

with the use of the pattern?

Page 51: prutt05_lec5

8/3/2019 prutt05_lec5

http://slidepdf.com/reader/full/prutt05lec5 51/51

Benefits and Dangers

+ support software reuse

+ language for discussing high-level problems

+ access to experience and knowledge

- limit creativity?

- needs a culture of reuse

- needs organisational education