45
CS540 Software Desi gn 2 Lecture 24 & 25 Purpose of this Lecture Purpose of this Lecture Introduce concept of “design Introduce concept of “design patterns” patterns” Discuss the concepts of Discuss the concepts of flexible object-oriented flexible object-oriented design design Show how to apply patterns to Show how to apply patterns to form good object-oriented form good object-oriented designs designs

Lecture 24 & 25: Design Patterns Anita S. Malik [email protected] Adapted from: David Van Camp's presentation at the PowerSoft User's Meeting and Training

Embed Size (px)

Citation preview

CS540 Software Design 2Lecture 24 & 25

Purpose of this LecturePurpose of this Lecture Introduce concept of “design Introduce concept of “design

patterns”patterns” Discuss the concepts of flexible Discuss the concepts of flexible

object-oriented designobject-oriented design Show how to apply patterns to Show how to apply patterns to

form good object-oriented designsform good object-oriented designs

CS540 Software Design 3Lecture 24 & 25

What are Patterns?What are Patterns? Many people say: "A pattern is a proven Many people say: "A pattern is a proven

solution to a problem in a context.“solution to a problem in a context.“ Pattern must:Pattern must:

solve a problemsolve a problem be related to a contextbe related to a context be general to fit in many situationsbe general to fit in many situations impart knowledge (information how the impart knowledge (information how the

pattern solves the problem)pattern solves the problem) have a unique namehave a unique name

CS540 Software Design 4Lecture 24 & 25

What are Design What are Design Patterns?Patterns?

““Descriptions of communicating Descriptions of communicating objects and classes that are objects and classes that are

customized to solve a general customized to solve a general design problem”design problem”

-- Gamma, et. al.-- Gamma, et. al.

CS540 Software Design 5Lecture 24 & 25

The Essential Elements The Essential Elements of a Design Patternof a Design Pattern

The Pattern NameThe Pattern Name The Problem it solvesThe Problem it solves The Solution it providesThe Solution it provides The Consequences (good and bad) of The Consequences (good and bad) of

using itusing it

CS540 Software Design 6Lecture 24 & 25

Design Pattern Design Pattern DescriptionDescription

CS540 Software Design 7Lecture 24 & 25

Name & ClassificationName & Classification

Prototype, a Creation design patternPrototype, a Creation design pattern

CS540 Software Design 8Lecture 24 & 25

IntentIntent

The Prototype design pattern creates new The Prototype design pattern creates new instances of classes by instances of classes by havinghaving initialized initialized prototype instances copy or clone prototype instances copy or clone themselvesthemselves

Useful when creating an instance is Useful when creating an instance is usually:usually: Time-consumingTime-consuming Very complexVery complex

Class copies itselfClass copies itself Process can be largely ignored by the creatorProcess can be largely ignored by the creator

CS540 Software Design 9Lecture 24 & 25

MotivationMotivation An example of the Prototype design pattern An example of the Prototype design pattern

would be in a GUI building toolwould be in a GUI building tool

For each graphic element which the user may For each graphic element which the user may customize and add to the application interface customize and add to the application interface (buttons, text boxes, etc.), the user has many (buttons, text boxes, etc.), the user has many options to choose for style, color, font, size, options to choose for style, color, font, size, etc.etc.

CS540 Software Design 10Lecture 24 & 25

MotivationMotivation

Keeping a single prototype of each GUI Keeping a single prototype of each GUI element on a palette for the user to choose element on a palette for the user to choose from allows the user to customize each type from allows the user to customize each type once and drag them onto the interface project once and drag them onto the interface project as desired.as desired.

Not only does this produce a consistent look Not only does this produce a consistent look and feel across the application, but the GUI and feel across the application, but the GUI building tool need only call the instance's building tool need only call the instance's clone() method each time it is dragged from clone() method each time it is dragged from the palette to the GUI, regardless of the the palette to the GUI, regardless of the specific class selected by the user.specific class selected by the user.

CS540 Software Design 11Lecture 24 & 25

ApplicabilityApplicability

Useful to design a system independent of Useful to design a system independent of how its objects are created, composed and how its objects are created, composed and representedrepresented

Dynamic object specificationDynamic object specification Specify the general class needed, but defer Specify the general class needed, but defer

specifics until execution timespecifics until execution time No class hierarchies of "factory" classes are No class hierarchies of "factory" classes are

neededneeded Can avoid building a class hierarchy of factories Can avoid building a class hierarchy of factories

parallelling the class hierarchy of productsparallelling the class hierarchy of products

CS540 Software Design 12Lecture 24 & 25

ApplicabilityApplicability Few different combinations of state in class instancesFew different combinations of state in class instances

May be more convenient to install a prototype for each state May be more convenient to install a prototype for each state and clone them, rather than instantiating the class manually, and clone them, rather than instantiating the class manually, each time with the appropriate stateeach time with the appropriate state

Useful when construction and initialization of an object is Useful when construction and initialization of an object is more complex or time consuming than simply cloning an more complex or time consuming than simply cloning an existing objectexisting object

Dynamic attribute specification for concrete class Dynamic attribute specification for concrete class objectsobjects Cloned concrete product object will have a complete copy of Cloned concrete product object will have a complete copy of

the prototype instance's statethe prototype instance's state Client can also specify attribute changes at creation timeClient can also specify attribute changes at creation time Initialization method parameters: "copy with changes Initialization method parameters: "copy with changes

capability"capability"

CS540 Software Design 13Lecture 24 & 25

ApplicabilityApplicability Allow automatic extension of the class Allow automatic extension of the class

inheritance tree for product classesinheritance tree for product classes Automatically accommodate all subclasses of concrete Automatically accommodate all subclasses of concrete

classesclasses Creation logic is always attached to the concrete Creation logic is always attached to the concrete

product class in clone() methodsproduct class in clone() methods Not in a separate concrete "factory" classNot in a separate concrete "factory" class

CS540 Software Design 14Lecture 24 & 25

StructureStructure

UML class diagramUML class diagram

CS540 Software Design 15Lecture 24 & 25

ParticipantsParticipants

Participants in the prototype patternParticipants in the prototype pattern Client - The client object asks the prototype Client - The client object asks the prototype

to clone itselfto clone itself Prototype - Data object defining an Prototype - Data object defining an

interface for creating clones of its selfinterface for creating clones of its self A "clone" function, returning a copy of the A "clone" function, returning a copy of the

original objectoriginal object ConcretePrototype - Implements the cloning ConcretePrototype - Implements the cloning

operation defined in the Prototype classoperation defined in the Prototype class Copies the data and state of the original objectCopies the data and state of the original object

CS540 Software Design 16Lecture 24 & 25

CollaborationsCollaborations

Collaborations between participants Collaborations between participants are initiated by the Clientare initiated by the Client

Prototypical instance of any Prototypical instance of any ConcretePrototypes to be used are ConcretePrototypes to be used are createdcreated Initialized to the desired state of an Initialized to the desired state of an

instance typical for the Client's useinstance typical for the Client's use Prototype is cloned whenever a new Prototype is cloned whenever a new

instance of this type is desiredinstance of this type is desired

CS540 Software Design 17Lecture 24 & 25

ConsequencesConsequences Consequences of using the Prototype design patternConsequences of using the Prototype design pattern Alternative to Abstract Factory (and Builder, somewhat)Alternative to Abstract Factory (and Builder, somewhat)

Instantiation code not in a separate concrete "factory" classInstantiation code not in a separate concrete "factory" class Isolates product (data) class details from the client for Isolates product (data) class details from the client for

instantiationinstantiation Streamlines client-side code for product instantiation processStreamlines client-side code for product instantiation process Eliminates case-by-class handling of instantiation (same method)Eliminates case-by-class handling of instantiation (same method) Requires a clone (or getClone) method in each Prototype subclassRequires a clone (or getClone) method in each Prototype subclass

Difficult to reuse prexisting classes or those from external sourcesDifficult to reuse prexisting classes or those from external sources A deepClone() method virtually requires all the member values of the A deepClone() method virtually requires all the member values of the

Prototype subclass be declared to implement SerializablePrototype subclass be declared to implement Serializable Classes with circular references to other classes can’t really be clonedClasses with circular references to other classes can’t really be cloned

CS540 Software Design 18Lecture 24 & 25

ConsequencesConsequences Every Prototype subclass instantiated has a minimum Every Prototype subclass instantiated has a minimum

of two instancesof two instances All used by client must be created as a prototype firstAll used by client must be created as a prototype first Possible performance drawback with large or many subclassesPossible performance drawback with large or many subclasses

Client can be configured with Prototype subclasses Client can be configured with Prototype subclasses dynamicallydynamically Can allow loading external classes into an application Can allow loading external classes into an application

dynamicallydynamically Works well with offline or distributed object registriesWorks well with offline or distributed object registries

Prototype subclass member values may require more Prototype subclass member values may require more access methodsaccess methods Any value that may differ from the prototype must be changed Any value that may differ from the prototype must be changed

through access methods rather than constructorsthrough access methods rather than constructors

CS540 Software Design 19Lecture 24 & 25

ImplementationImplementation

Implementation issues of the Implementation issues of the Prototype design patternPrototype design pattern

Determine mechanism for generation, Determine mechanism for generation, management, and access of initial management, and access of initial prototype instances by client:prototype instances by client: Generated externally, passed to client Generated externally, passed to client

processprocess Managed by a prototype manager,Managed by a prototype manager,

including prototype creationincluding prototype creation

CS540 Software Design 20Lecture 24 & 25

Sample CodeSample Code

Client - The client object asks the Client - The client object asks the prototype to clone itselfprototype to clone itself

public class Client {public class Client {private ConcretePrototype private ConcretePrototype

cpPrototype = cpPrototype = new new ConcretePrototype();ConcretePrototype();

. . .. . .current = current =

cpPrototype.getClone();cpPrototype.getClone();. . .. . .

}}

CS540 Software Design 21Lecture 24 & 25

Sample CodeSample Code

Prototype - Data object defining an Prototype - Data object defining an interface for creating clones of its selfinterface for creating clones of its selfpublic class Prototype implements Cloneable {public class Prototype implements Cloneable {

//protected ClassMemberValue //protected ClassMemberValue memberValue;memberValue;

public Object clone() {public Object clone() {try {try {

Prototype cloned = null;Prototype cloned = null;cloned = (Prototype) super.clone();cloned = (Prototype) super.clone();

//cloned.memberValue = memberValue;//cloned.memberValue = memberValue;// Or use deep copy// Or use deep copy

return cloned;return cloned;}}

CS540 Software Design 22Lecture 24 & 25

Sample CodeSample Code

catch(Exception e) {catch(Exception e) {System.out.println(e.getMessage());System.out.println(e.getMessage());return null;return null;

}}}}

public Prototype getClone() {public Prototype getClone() { // // Can be abstractCan be abstract

Prototype cloned = null;Prototype cloned = null;cloned = (Prototype) this.clone();cloned = (Prototype) this.clone();return cloned;return cloned; // May be NULL// May be NULL

}}}}

CS540 Software Design 23Lecture 24 & 25

Sample CodeSample CodeConcretePrototype - Implements the cloning ConcretePrototype - Implements the cloning

operation defined in the Prototype classoperation defined in the Prototype class Copies the data and state of the original objectCopies the data and state of the original object

public class ConcretePrototype extends Prototype {public class ConcretePrototype extends Prototype {//protected ClassMemberValue //protected ClassMemberValue subclassSpecificAttribute;subclassSpecificAttribute;public ConcretePrototype getClone() {public ConcretePrototype getClone() {

ConcretePrototype cloned = null;ConcretePrototype cloned = null;cloned = (ConcretePrototype) super.clone();cloned = (ConcretePrototype) super.clone();//equivalent to: cloned = super.getClone();//equivalent to: cloned = super.getClone();

//cloned.subclassSpecificAttribute =//cloned.subclassSpecificAttribute = subclassSpecificAttribute; subclassSpecificAttribute;

// Or use deep copy// Or use deep copyreturn cloned;return cloned; // May be NULL// May be NULL

}}}}

CS540 Software Design 24Lecture 24 & 25

More InformationMore Information You find the Prototype Pattern may help You find the Prototype Pattern may help

you? Read more:you? Read more: Solution:Solution: Some more detailed view what Some more detailed view what

the Pattern is good for.the Pattern is good for. Applicability: Applicability: Tells you in which Tells you in which

environment the Pattern makes sense.environment the Pattern makes sense. Consequences: Consequences: This very important part This very important part

talks about talks about disadvantagesdisadvantages and and pitfallspitfalls..

……often there is additional information often there is additional information available.available.

CS540 Software Design 25Lecture 24 & 25

Make Your DecisionMake Your Decision Ask yourself: “Is this pattern useful in Ask yourself: “Is this pattern useful in

my case?”my case?” The description of the pattern can help The description of the pattern can help

you to make a decision: You know…you to make a decision: You know…

……what this pattern intents to solvewhat this pattern intents to solve ……how it can be implementedhow it can be implemented ……the positive and the negative aspectsthe positive and the negative aspects

You know this in advance, You know this in advance,

before implementation and testing.before implementation and testing.

CS540 Software Design 26Lecture 24 & 25

No Magic!No Magic!

The Prototype Pattern contains nothing The Prototype Pattern contains nothing magicalmagical

Easy to understandEasy to understand Easy to implementEasy to implement For sure you already used Patterns without For sure you already used Patterns without

knowing itknowing it

Design Patterns are nothing mystic - Design Patterns are nothing mystic - disappointed?disappointed?

CS540 Software Design 27Lecture 24 & 25

Object Oriented DesignObject Oriented Design

Object-Oriented design and Object-Oriented design and programming is widely spread and programming is widely spread and well known by programmers.well known by programmers.

Thinking in objects and classes are Thinking in objects and classes are good methods in software good methods in software development.development.

CS540 Software Design 28Lecture 24 & 25

Patterns and ObjectsPatterns and Objects

The implementation of Patterns were The implementation of Patterns were usually described as class-diagrams.usually described as class-diagrams.

Some Patterns (like Prototype) are Some Patterns (like Prototype) are about “creating” objects which only about “creating” objects which only makes sense in an object-oriented makes sense in an object-oriented environment.environment.

OO-programming is OO-programming is not mandatorynot mandatory for Patterns. (Patterns describe a for Patterns. (Patterns describe a solution for specific problems.)solution for specific problems.)

CS540 Software Design 29Lecture 24 & 25

Pattern CataloguesPattern Catalogues Patterns (like Prototype) were collected Patterns (like Prototype) were collected

in Catalogues.in Catalogues. In the Internet e.g.: In the Internet e.g.:

http://www.patterndigest.comhttp://www.patterndigest.com In books like: “Design Patterns”In books like: “Design Patterns” Catalogues contain complete Pattern-Catalogues contain complete Pattern-

Description: Name, Intent, Diagram, Description: Name, Intent, Diagram, Solution, Consequences, …Catalogues Solution, Consequences, …Catalogues usually contain references to related usually contain references to related Patterns, related problems, related Patterns, related problems, related environments, …environments, …

CS540 Software Design 30Lecture 24 & 25

Pattern Catalogues (contd)Pattern Catalogues (contd) Catalogues (usually) sort Design Catalogues (usually) sort Design

Patterns by categories:Patterns by categories: Structural Patterns Structural Patterns Creational PatternsCreational Patterns Behavioural Patterns Behavioural Patterns Relationship PatternsRelationship Patterns Downcasting PatternsDowncasting Patterns Property PatternsProperty Patterns

CS540 Software Design 31Lecture 24 & 25

Pattern Catalogues (contd)Pattern Catalogues (contd)

Usage of catalogues:Usage of catalogues: Browse through the catalogues for Browse through the catalogues for

Patterns matching to your problem.Patterns matching to your problem. Study class-diagrams before Study class-diagrams before

implementingimplementing Some catalogues also contain example Some catalogues also contain example

code (usually in Java or C++)code (usually in Java or C++)

CS540 Software Design 32Lecture 24 & 25

The GOF’s Design The GOF’s Design PatternsPatterns

Pattern NamePattern Name JurisdictionJurisdiction IntentIntent MotivationMotivation ApplicabilityApplicability ParticipantsParticipants

CollaborationsCollaborations Structure DiagramStructure Diagram ConsequencesConsequences ImplementationImplementation ExamplesExamples See AlsoSee Also

Highly verbose with good direction and suggestions for use, including

interactions with other patterns. Each pattern contains:

CS540 Software Design 33Lecture 24 & 25

Some Other PatternsSome Other Patterns

Some other example Patterns:Some other example Patterns:

IteratorIterator CommandCommand

CS540 Software Design 34Lecture 24 & 25

The Iterator PatternThe Iterator Pattern Name:Name: Iterator (Behavioural Iterator (Behavioural

Pattern)Pattern) Intent:Intent: Provide a way to access the Provide a way to access the

elements of a aggregate object elements of a aggregate object without exposing its underlying without exposing its underlying representation. representation.

Diagram:Diagram:+getIterator()+getElement()

Aggregate

+first()+last()+next()+prev()+current()

-current

Iterator

Element

1

*

«uses»

Client

«uses»«uses»

<<creates>>

CS540 Software Design 35Lecture 24 & 25

The Iterator Pattern The Iterator Pattern (contd)(contd)

The Client uses Iterator-Objects to walk The Client uses Iterator-Objects to walk through any aggregate.through any aggregate.

Replaces loops ( for, while, etc.)Replaces loops ( for, while, etc.) Easy to implementEasy to implement Abstraction for accessing dataAbstraction for accessing data Simple interface for all kind of Simple interface for all kind of

aggregatesaggregates Use more than one iterator at the same Use more than one iterator at the same

timetime

CS540 Software Design 36Lecture 24 & 25

The Iterator Pattern The Iterator Pattern (contd)(contd)$agg$agg =& =& newnew aggregate(); aggregate(); // instantiate the // instantiate the

aggregateaggregate$iter1$iter1 = = $agg$agg->getIterator(); ->getIterator(); // get a matching // get a matching

iteratoriterator$ele$ele = = $iter1$iter1->first(); ->first(); // get the first element// get the first elementwhilewhile( ( $ele$ele ) ){{ $ele$ele->doSomething(); ->doSomething(); // perform operation// perform operation $ele$ele = = $iter1$iter1->next(); ->next(); // get the next element// get the next element}}$iter2$iter2 = = $agg$agg->getIterator(); ->getIterator(); // get independent // get independent

iteratoriterator$ele$ele = = $iter2$iter2->last(); ->last(); // get the last element// get the last element

CS540 Software Design 37Lecture 24 & 25

Command PatternCommand Pattern Name:Name: Command (Behavioural Pattern) Command (Behavioural Pattern)

Intent:Intent: Encapsulate a request as a parameterized object; Encapsulate a request as a parameterized object; allow different requests, queue or log requests and support allow different requests, queue or log requests and support undoable operationsundoable operations

Diagram:Diagram:

+execute()

-state

SpecCommand

+execute()

Command

+action()

Receiver

Invoker

1 *

Client

CS540 Software Design 38Lecture 24 & 25

Command Pattern (contd)Command Pattern (contd)

Some benefits:Some benefits:

Decouples objects from operationsDecouples objects from operations Allows logging, “do”, “undo”Allows logging, “do”, “undo” Easy to implement Macro-Commands Easy to implement Macro-Commands

CS540 Software Design 39Lecture 24 & 25

SummarizeSummarize Patterns names may ease Patterns names may ease

communicationcommunication Patterns ease understanding Patterns ease understanding

softwaresoftware Patterns are proven solutionsPatterns are proven solutions Patterns are well documentedPatterns are well documented Benefits and disadvantages are Benefits and disadvantages are

known in advanceknown in advance

CS540 Software Design 40Lecture 24 & 25

A Simple Undo/Redo A Simple Undo/Redo ExampleExample

CS540 Software Design 41Lecture 24 & 25

Receiver

Action()

Invoker Command

Execute()

SpecificCommand

state

Execute()

Client

reciever.action()

GOF Command PatternGOF Command Pattern

Create Specific Commands

Source: Design Patterns: Elements of Reusable Object-Oriented Software, Gamma, Helm, Johnson & Vlissides

CS540 Software Design 43Lecture 24 & 25

Memento PatternMemento Pattern

Originator

state

SetMemento()CreateMemento()

m = create Mementom.SetState (state)return m

state = m.GetState()

Memento

state

SetState()GetState()

Caretaker

Source: Design Patterns: Elements of Reusable Object-Oriented Software, Gamma, Helm, Johnson & Vlissides

CS540 Software Design 45Lecture 24 & 25

Basic Undo/Redo PatternBasic Undo/Redo Pattern

Client

Do (cmd)Undo()Redo()

Command

basicState

SetState (state)Do ()Undo ()Redo ()

SpecificCommand

specificState

SetState (state)Do ()Undo ()

UndoStack

commands[]

Do (cmd)Undo ()Redo ()CanUndo ()CanRedo ()

Target

state

Command()

cmd = create SpecificCommandcmd.SetState (state) Client.Do ( cmd )

commands [top] = cmdcmd.Do ()

{LIFO}

This.Do ()

UndoStack.Do (cmd)

CS540 Software Design 47Lecture 24 & 25

Undo / Redo Stack Undo / Redo Stack OperationOperation

1. Stack after doing 4 commands:

undo top redo top

InsertRow Edit Edit Sort

2. Stack after undoing 2 commands:InsertRow Edit Edit Sort

undo top redo top

3. Stack after redoing 1 command:

undo top redo top

InsertRow Edit Edit Sort

4. Stack after doing another command:InsertRow Edit Edit CopyRow

undo top redo top

CS540 Software Design 51Lecture 24 & 25

Patterns Web SitesPatterns Web Sites R. Johnson’s Patterns Home Page:R. Johnson’s Patterns Home Page:

http://st-www.cs.uiuc.edu/users/patterns/patterns.htmlhttp://st-www.cs.uiuc.edu/users/patterns/patterns.html

The primary source for online pattern information.The primary source for online pattern information.

The Portland Pattern Repository:The Portland Pattern Repository:http://c2.com/ppr/index.htmlhttp://c2.com/ppr/index.html

Another really good source for patternsAnother really good source for patterns

Objects International (P. Coad):Objects International (P. Coad):http://www.oi.com/oi_home.htmlhttp://www.oi.com/oi_home.html

‘‘Stratagies and Patterns Handbook‘ Windows Stratagies and Patterns Handbook‘ Windows Help file and other free stuff.Help file and other free stuff.

CS540 Software Design 52Lecture 24 & 25

Other Design Pattern Other Design Pattern SourcesSources Gamma, Helm, Vlissides, Johnson: Design Gamma, Helm, Vlissides, Johnson: Design

Patterns, 1994Patterns, 1994 Design Patterns for Object-Oriented Software Design Patterns for Object-Oriented Software

DevelopmentDevelopment, W. Pree, Addison-Wesley, 1995, W. Pree, Addison-Wesley, 1995 Pattern Languages of Program DesignPattern Languages of Program Design, Coplien & , Coplien &

Schmidt, eds. Addison-Wesley, 1995Schmidt, eds. Addison-Wesley, 1995 Graig Larman: Applying UML and Patterns, 2001Graig Larman: Applying UML and Patterns, 2001 Van Duyne, Hong, Landay: Design of Sites, 2002Van Duyne, Hong, Landay: Design of Sites, 2002 Pattern Homepage Pattern Homepage http://http://www.hillside.netwww.hillside.net Pattern Digest Pattern Digest http://http://www.patterndigest.comwww.patterndigest.com and many other books and articles!and many other books and articles!