introduction to design patterns why a design pattern · 6 creational pattern factory method: define...

12
1 Introduction to Design Patterns Nasreddine Aoumeur E-mail: [email protected]. uk Why a Design Pattern Reusability: one of the basis for an efficient and actual SE discipline Helping new designers to have a more flexible and reusable design Improving the documentation and maintenance of existing system by furnishing an explicit specification of class and object interactions and their intent. History of Design Pattern 1979: Christopher Alexander,architect, “The Timeless Way of Building”, Oxford Press 1987: OOPSLA (Object Oriented Programming System),Orlando, presentation of design pattern to the community OO by Ward Cunningham and Kent Beck. Pattern origins and history Kent Beck and Ward Cunningham, Textronix, OOPSLA'87 (used Alexander's "pattern" ideas for Smalltalk GUI design) Erich Gamma, Ph. D. thesis, 1988-1991 James Coplien, Advanced C++ Idioms book, 1989-1991 PLoP Conferences and books, 1994-present Buschmann, Meunier, Rohnert, Sommerland, Stal, Pattern -Oriented Software Architecture: A System of Patterns (“POSA book POSA book”) 1995: Group of Four alias E.Gamma, R.Helm,R.Johnson and J.Vlissides : “Design Pattern:Elements of Reusable OO softwareDefinition … a fully realized form, original, or model accepted or proposed for imitation…[dictionary] ... 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 [Alexander] … the abstraction from a concrete form which keeps recurring in specific non-arbitrary contexts [Riehle] …both a thing and the instructions for making the thing [Coplien] ...a literary format for capturing the wisdom and experience of expert designers, and communicating it to novices Properties Patterns do... Patterns do... provide common vocabulary provide “shorthand” for effectively communicating complex principles help document software architecture capture essential parts of a design in compact form show more than one solution describe software abstractions Patterns do not... Patterns do not... provide an exact solution solve all design problems only apply for object-oriented design

Upload: others

Post on 28-Jul-2020

4 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Introduction to Design Patterns Why a Design Pattern · 6 Creational Pattern Factory Method: Define an interface for creating an object but let subclasses decide which class to instantiate

1

Introduction to Design Patterns

Nasreddine Aoumeur

E-mail: [email protected]

Why a Design PatternReusability: one of the basis for an efficientand actual SE discipline

Helping new designers to have a moreflexible and reusable design

Improving the documentation andmaintenance of existing system by furnishingan explicit specification of class and objectinteractions and their intent.

History of Design Pattern1979: Christopher Alexander,architect, “TheTimeless Way of Building”, Oxford Press

1987: OOPSLA (Object Oriented ProgrammingSystem),Orlando, presentation of designpattern to the community OO by WardCunningham and Kent Beck.

Pattern origins and historyKent Beck and Ward Cunningham, Textronix,OOPSLA'87(used Alexander's "pattern" ideas for SmalltalkGUI design)Erich Gamma, Ph. D. thesis, 1988-1991James Coplien, Advanced C++ Idioms book,1989-1991PLoP Conferences and books, 1994-presentBuschmann, Meunier, Rohnert, Sommerland,Stal, Pattern -Oriented Software Architecture:A System of Patterns ((““POSA bookPOSA book””))1995: Group of Four alias E.Gamma,R.Helm,R.Johnson and J.Vlissides : “DesignPattern:Elements of Reusable OO software”

Definition… a fully realized form, original, or model accepted orproposed for imitation…[dictionary]... describes a problem which occurs over and overagain in our environment, and then describes the coreof the solution to that problem, in such a way thatyou can use this solution a million times over, withoutever doing it the same way twice [Alexander]… the abstraction from a concrete form which keepsrecurring in specific non-arbitrary contexts [Riehle]

…both a thing and the instructions for making thething [Coplien]

...a literary format for capturing the wisdom andexperience of expert designers, and communicating itto novices

Properties

Patterns do...Patterns do...provide common vocabularyprovide “shorthand” for effectively communicatingcomplex principleshelp document software architecturecapture essential parts of a design in compact formshow more than one solutiondescribe software abstractions

Patterns do not...Patterns do not...provide an exact solutionsolve all design problemsonly apply for object-oriented design

Page 2: Introduction to Design Patterns Why a Design Pattern · 6 Creational Pattern Factory Method: Define an interface for creating an object but let subclasses decide which class to instantiate

2

Patterns can be

non-generative (Gamma patterns) observed in a system descriptive and passive

generative generate systems or parts of systems perspective and active

Ingredients

Pattern

Solution

Problem

Context

a design situation giving rise to a design problem

a form or rule that can be applied to resolve these forces

a set of forces occuring in that context

Example Example –– window place window placeforces he wants to sit down and be comfortable he is drawn toward the light

solution in every room, make at least one window into a

“window place”

Types of software patterns

design patterns (software design)[Buschmann-POSA] architectural (systems design) design (micro-architectures) [Gamma-GoF] idioms (low level)

analysis patterns (recurring & reusable analysismodels) [Flower]organization patterns (structure oforganizations/projects)process patterns (software process design)domain-specific patterns (ditribution, evolution,…)

Alexandrian form (canonical form)

Name : meaningful nameProblem : the statement of the problemContext : a situation giving rise to a problemForces : a description of relevant forces and

constraintsSolution : proven solution to the problemExamples : sample applications of the patternResulting context (force resolution)

the state of the system after pattern hasbeen applied

Alexandrian form (canonical form)

Rationale : explanation of steps or rulesin the pattern

Related patterns : static and dynamicrelationship

Known use : occurrence of the patternand its application within existingsystem

GoF formatPattern name and classificationIntent : what does pattern do / when the

solution worksAlso known as : other known names of pattern

(if any)Motivation : the design problem / how class and

object structures solve the problemApplicability : situations where pattern can be

appliedStructure :a graphical representation of classes

in the patternParticipants :the classes/objects participating

and their responsibilitiesCollaborations : of the participants to carry out

responsibilities

Page 3: Introduction to Design Patterns Why a Design Pattern · 6 Creational Pattern Factory Method: Define an interface for creating an object but let subclasses decide which class to instantiate

3

GoF format

Consequences : trade-offs, concernsImplementation : hints, techniquesSample code : code fragment showing possible

implementation

Known uses : patterns found in real systems

Related patterns : closely related patterns

Pattern templates[PATTERN-NAME]Author[YOUR-NAME] ([[email protected]]).Last updated on [TODAY'S-DATE]Context[PARAG-1][PARAG-2]Problem [ONE-ASPECT] [ANOTHER-ASPECT]ExamplesForces 1.[FORCE-1] 2.[FORCE-2]Design[PARAG-1][PARAG-2]An Implementation [SOME-CODE]ExamplesVariants [VARIANT] [ANOTHER-VARIANT]See Also [ANOTHER-REF]

http://hillside.net/patterns/Writing/Lea.html

•http://hillside.net/patterns/template.html•http://www.paterndepot.com/pages (Templates)

More pattern templates:More pattern templates:

IF you find yourself in CONTEXT for example EXAMPLES, with PROBLEM, entailing FORCES THEN for some REASONS, apply DESIGN FORM AND/OR RULE to construct SOLUTION leading to NEW CONTEXT and OTHER PATTERNS

http://g.oswego.edu/dl/pd-FAQ/pd-FAQ.html

What Is a Design Pattern

A design pattern is a descriptions of communicatingobjects and classes that are customized to solve ageneral design problem in a particular context

A pattern is made by four elements: name problem solution consequences

Name of Design Pattern

Describe a design problems and its solutions in aword or two

Used to talk about design pattern with our colleagues

Used in the documentation Increase our design vocabulary Have to be coherent and evocative

Problem

Describes when to apply the patterns

Explains the problem and its context

Sometimes include a list of conditions that must bemet before it makes sense to apply the pattern

Have to occurs over and over again in ourenvironment

Solution

Describes the elements that make up the design,their relationships, responsibilities andcollaborations

Does not describe a concrete design orimplementation

Has to be well proven in some projects

Page 4: Introduction to Design Patterns Why a Design Pattern · 6 Creational Pattern Factory Method: Define an interface for creating an object but let subclasses decide which class to instantiate

4

Consequences

Results and trade-offs of applying the pattern

Helpful for describe design decisions, forevaluating design alternatives

Benefits of applying a pattern (performance,time, size,…).

Impacts on a system’s flexibility,extensibilityor portability

Description of Design Pattern

Pattern name and classificationPattern name and classification contains the essence of pattern succinctly Become part of your design vocabulary

IntentIntent What does the pattern do ? What particular problem does it address ?

Description of Design Pattern

MotivationMotivation Illustrate a design problem and how the class and the

object structures solve the problem

ApplicabilityApplicability In which situations the pattern can be applied?

How can you recognize these situations?

Description of Design Pattern

StructureStructure Graphical representation of the classes and their

collaborations in the pattern

ParticipantsParticipants Class Objects Responsibilities

Description of Design PatternCollaborationsCollaborations How the participants collaborate to carry out their

responsibilities

ConsequencesConsequences How does the pattern support its objectives? What are the trade-offs and results of using the

pattern?

Description of Design Pattern

ImplementationImplementation : a sketch : a sketch

Sample CodeSample Code : a sketch : a sketch

Known UsesKnown Uses Examples of the pattern found in real systems

Page 5: Introduction to Design Patterns Why a Design Pattern · 6 Creational Pattern Factory Method: Define an interface for creating an object but let subclasses decide which class to instantiate

5

Description of Design Pattern

Related PatternsRelated Patterns What design patterns are closely related to this one?

What are the important differences?

By purpose and by scope

Creational patternsCreational patterns

Abstract the instantiation process Make a system independent to its realization Class Creational use inheritance to vary the instantiated

classes Object Creational delegate instantiation to an another object

Classification of DesignPattern

Classification of DesignPattern

Structural patternsStructural patterns

Class Structural patterns concern the aggregationof classes to form largest structures

Object Structural pattern concern the aggregationof objects to form largest structures

Classification of DesignPattern

Behavioral patternsBehavioral patterns

Concern with algorithms and assignment ofresponsibilities between objects

Describe the patterns of communication betweenclasses or objects

Behavioral class pattern use inheritance todistribute behavior between classes

Behavioral object pattern use object compositionto distribute behavior between classes

Classification of design patterns

InterpreterAdapterFactory Method

Visitor

Strategy

StateProxy

ObserverFlyweight

MementoFaçade

MediatorDecoratorSingleton

IteratorCompositePrototype

CommandBridgeBuilder

Chain ofResponsibility

AdapterAbstract Factory

Template Method

BehavioralBehavioralStructuralStructuralCreationalCreational

ObjectObject

ClassClasspurpose

Scope

Creational Patterns

Singleton Ensure a class only has one instance Provide a global point of access to it

Abstract Factory: Provide an interface for creating families of related

or dependent objects without specifying theirconcrete classes

Page 6: Introduction to Design Patterns Why a Design Pattern · 6 Creational Pattern Factory Method: Define an interface for creating an object but let subclasses decide which class to instantiate

6

Creational Pattern

Factory Method: Define an interface for creating an object but let

subclasses decide which class to instantiate Lets a class defer instantiation to subclasses

Prototype Specify the kinds of objects to create using a

prototypical instance Create new objects by copying this prototype

Creational Pattern

Builder: Separate the construction of a complex object from

its representation so that the same constructionprocess can create different representations

Structural Pattern

Composite Compose objects into tree structures to represent

part-whole hierarchies Lets clients treat individual objects and

compositions of objects uniformly

Decorator Attach additional responsibilities to an object

dynamically Provide a flexible alternative to subclassing for

extending functionality

Structural Pattern

Adapter Convert the interface of a class into another

interface clients expect Lets classes work together that couldn’t otherwise

because of incompatible interfaces

Bridge Decouple an abstraction from its implementation

so that the two can vary independently

Structural Pattern

Façade Provide a unified interface to a set of interfaces in

a subsystem Defines an higher-level interface that makes the

system easier to use

Flyweight Use sharing to support large numbers of fine-

grained objects efficiently

Structural Pattern

Proxy Provide a surrogate or placeholder for another object

to control access to it

Page 7: Introduction to Design Patterns Why a Design Pattern · 6 Creational Pattern Factory Method: Define an interface for creating an object but let subclasses decide which class to instantiate

7

Behavioral Pattern

Iterator Provide a way to access the elements of an

aggregate object without exposing itsrepresentation

Command Encapsulate a request as an object, thereby

letting you parameterize clients with differentrequests

Behavioral Pattern

Interpreter Given a language, define a representation for its

grammar along with an interpreter that uses therepresentation to interpret sentences in thelanguage

Mediator Define an object that encapsulate how a set of

objects interact Promotes loose coupling by keeping objects from

referring to each other explicitly Lets you vary their interaction independently

Behavioural patterns : The State

Motivation Objects often have internal states (MODE1,

MODE2,…)with related behaviour. Examples are lift,vending-machine, …

A Direct native implementation

Public class Context{

public static final int MODE1 = 0;public static final int MODE1 = 1;private int mode;. . . .

Public void request(){ if (mode == MODE1)

{code1}else if (mode == MODE2)

{Code2}}….} // Context

Problem with this implemetation

The program becomes rapidly intractable. Difficult to maintain : any change to the set of

modes requires a change to every method thatdepends on the mode.

Not efficient : each time we have to test for theappropriate mode.

Behavioral patterns : The State

The state pattern proposes explicit subclasses tocapture each mode.

The choice between different suclasses (i.e. the onecorrsponding to invoked mode) is achieved throughpolymorphism….and not by the programmer.

Page 8: Introduction to Design Patterns Why a Design Pattern · 6 Creational Pattern Factory Method: Define an interface for creating an object but let subclasses decide which class to instantiate

8

Behavioral patterns : The State

StateHandle()request()

State1

Handle()

State.handle()

Context

State2

Handle()

State

Code1 Code2

Behavioral patterns : The State

Benefits

Context1 : interface for clients; it maintains a Stateinstance to reflect the mode.

State : Abstract suoerclass of classes representingdifferent modes.

State1, 2… : each subclass of State implements thebehaviour of a specific mode.

Behavioral patterns : The State

Public class Context1{Private State state;

. . . .Public void request() { state.handle();}….} // Context1Abstract class State{ …..

public abstract void handle()} // State

Behavioral patterns : The State

class State1 extends State{

Private void handle() { code1 }} // State1

class State2 extends State{

Private void handle() { code2 }} // State1

Behavioral patterns : The State

Benefits Location of behavior : New states and transitions

can be added by defining new State subclasses. Code understandability and maintainability. State transitions are made explicit : State rather

than assignments

Behavioral patterns : The State

Example A common use of the state pattern is to reorganize

applications such as drawing tools. Drawing tools have different behaviour for

cooresponding modes (shape creation, shapeselection or text editing)

But responds to the same basic sets of events (e.g.mouse events).

Page 9: Introduction to Design Patterns Why a Design Pattern · 6 Creational Pattern Factory Method: Define an interface for creating an object but let subclasses decide which class to instantiate

9

Behavioral patterns : The State

mousePressed()keyPressed()

DrawingController mousePressed()keyPressed()

Tool

mousePressed()keyPressed()

TextToolmousePressed()

keyPressed()

SelectionToolmousePressed()

keyPressed()

CreationTool

currentTool

Behavioral patterns : The Template Method

It defines the schema of an algorithm in a superclassmethod, deferring details to subclasses.

Details (steps/parts) are redefined using subclasses. So, common part of an algorithm are factored out

into the superclass….No duplication.

Behavioral patterns : The State

Behavioral patterns : The TemplateMethod

Generic classTemplatemethod()

hookMethod1()hookMethod2()

ConcreteClass1

hookMethod1()hookMethod2()

ConcreteClass2

hookMethod1()hookMethod2()

….

hookMehtod1()

hookMethod2()

This super-class defines thetemplate method skeletonalgorithm, calling for one ormore hook methods…theycan abstract or have defaultcode.

This super-class defines thetemplate method skeletonalgorithm, calling for one ormore hook methods…theycan abstract or have defaultcode.

It implements one version ofthe hook methods

It implements one version ofthe hook methods

Behavioral patterns : The Template Method

Example

MSc and BSc students, with common attributesstudentId and numberPassed and a common methodaddMark(int m).

For MSc numberPassed is incremented only if m isgreater than 50. The same of BSc but the mark hasto be just more than 40.

Instead of duplicating, the pattern solution is toconsider addMark as a generic using a hook methodisPass (with different implementation in tworespective subclasses).

Behavioral patterns : The TemplateMethod

Public GeneralStudent (int id){ student id;}Abstract protected boolean isPass(int mark); /* Hook method */

Public void addMark(int m){if (isPass(m))}{numberPassed++};

}}

Class MScStudent extends GeneralStudent{ public MScStudent (int id){ super id:}

Protected boolean isPass(int m){ return (m >= 50) ;

Behavioral patterns : The TemplateMethod

Class BScStudent extends GeneralStudent{ public BScStudent (int id){ super id:}

Protected boolean isPass(int m){ return (m >= 40) ;

Page 10: Introduction to Design Patterns Why a Design Pattern · 6 Creational Pattern Factory Method: Define an interface for creating an object but let subclasses decide which class to instantiate

10

Behavioral patterns : The TemplateMethod

Class MScStudent extends GeneralStudent{ public MScStudent (int id){ super id:}

Protected boolean isPass(int m){ return (m >= 50) ;

Behavioral patterns : The State

Behavioral patterns : The TemplateMethod

GeneralStudent

addMark(m:int)isPass() : bool

MScStudent

isPass() : bool

BScStudent

isPass() : bool

If (isPass(m))

{numberPassed++}

IsPass implem. IsPass implem.

Behavioral patterns : The Visitor

It aims to separate the algorithms which operate overa data structure from the definition of that datastructure.

With that, algorithms and data may varyindependently.

Behavioral patterns : The State

Behavioral patterns : The Visitor<<interface>>

Element

Accept(Visitor v)

ElementA

Accept(Visitor v)

For all e instanceof Element

{if (children.contains(e))

{e.accept(v);}}

v.visit(this)

v.visit(this)v.visit(this)

ElementB

Accept(Visitor v)

Composite Element

Accept(Visitor v)

children*

The data structuresuperclass. It has anabstract accept method toprocess general visitors

The data structuresuperclass. It has anabstract accept method toprocess general visitors

Behavioral patterns : The State

Behavioral patterns : The Visitor<<interface>>

Visitor

Visit(ElementA e)Visit(ElementB e)Visit(Composite Element e)

ElementB

*

ConcreteVisitor

Visit(ElementA e)Visit(ElementB e)Visit(Composite Element e)

Behavioral patterns : The State

Behavioral patterns : The Visitor

Expression

Variable

Name:string

Basic expression

Value : stringType: integer

Binary Expression

Operator : String

left

right

Page 11: Introduction to Design Patterns Why a Design Pattern · 6 Creational Pattern Factory Method: Define an interface for creating an object but let subclasses decide which class to instantiate

11

Behavioral patterns : The Visitor

Example

Several functions (algorithms) are to beimplemented to extract properties of andlocally modify elements.1. Compute(ListofAllvariables).2. Rename(Varibales)…if s is the name of the

variable v (v.getName) then v.setName(String).

Behavioral patterns : The VisitorAbstract class Expression{public abstract void accept}

Class BinaryExpression extends Expression{private Expression left;Private expression right;Private string operator;

Public void accept(Visitor v){left.accept(v) right.accept(v); v.visit(this);}….}

Behavioral patterns : The VisitorClass BasicExpression extends Expression {private String value; private int type;

Public void accept(Visitor v) { v.visit(this);}}

Class Variable extends Expression {private String name;Public avoid setName(String nme) {name = nme;}

Public String getname() { return name; }

Public void accept(Visitor v) { v.visit(this);}

Behavioral patterns : The VisitorAbstract class Visitor {public abstract void visit (Variable v); public abstract void visit (BasicVariable be); public abstract void visit (BinaryExpression be);

private int type; Public void accept(Visitor v) { v.visit(this);}}

Behavioral patterns : The VisitorImport java.util.Vector;Public class GetUsesVisitor extends Visitor{ private Vector vars = new Vector();

Public void visit(Variable v){if (vars.contains(v.getName()) {} else { vars.add(v.getName());}} Public void visit(BasicExpression be) {} Public void visit(BinaryExpression be) {}}

Behavioral patterns : The VisitorImport java.util.Map;Import java.util.HashMap;

Public class RenameVisitor extends Visitor{private Map replacements = new HashMap(); }

Public void setReplacement(String old, String rep) { replacements.put(old,rep); }

Public void visit(Variable v) {String s = (String) replacements.get(v.getName());If (s != null){ v.setName(s);}}

Public void visit(BasicExpression be) {}Public void visit (BinaryExpression be) {}}

Page 12: Introduction to Design Patterns Why a Design Pattern · 6 Creational Pattern Factory Method: Define an interface for creating an object but let subclasses decide which class to instantiate

12

BibliographyFor the pattern catalogue:

Erich Gamma, Richard Helm,RalphJohnson,John Vlissides. Design Patterns:Elements of Reusable Object-OrientedSoftware. ADDISON-WESLEY 1995

For the pattern origin:Cristopher Alexander. The Timeless Way ofBuilding. Oxford Press 1979

James O.Coplien,Douglas C.Schmidt.PatternLanguages of Program Design. ADDISON-WESLEY 1995

Conclusions

At present, the software community is usingpattern largely for software architecture anddesignMore recently the software community isusing pattern also for software developmentprocesses and to organizationsSeveral object-oriented software designnotations/methods have added support forthe modeling and representation of designpatterns