Software Design and Construction 1 SOFT2201 / COMP9201 Introduction to Design Patterns
Dr. Grane School of Computer Science
The University of 1
Copyright warning
COMMONWEALTH OF AUSTRALIA Copyright Regulations 1969 WARNING
This material has been reproduced and communicated to you by or on behalf of the University of Sydney
pursuant to Part VB of the Copyright Act 1968 (the Act).
The material in this communication may be subject to copyright under the Act. Any further copying or communication of this material by you may be the subject of copyright protection under
the Act.
Do not remove this notice.
The University of 2
Agenda
– DesignPatterns
– GoFDesignPatterns
– CreationalDesignPatterns – FactoryMethodPattern
– BuilderPattern
The University of 3
What is a Design Pattern?
The University of 4
Design Patterns
– A pattern is a description of a problem and its solution
– Tried and tested ideas for a recurring design problem
– Not a readily coded solution, but rather the solution path to a common programming problem
– Design or implementation purpose
structure that achieves a particular
The University of 5
Essential Components of a Pattern
– Thepatternname
– e.g.,FactoryMethod
– Theproblem
– Thepatternisdesignedtosolve(i.e.,whentoapplythepattern)
– Thesolution
– Thecomponentsofthedesignandhowtheyrelatedtoeachother
– Consequence
– Theresultsandtrade-offsofapplyingthepattern
– Advantagesanddisadvantagesofusingthepattern
The University of 6
Gang of Four Patterns (GoF)
• Official design pattern reference
• Famous and influential book about design patterns • Recommended for students who wish to become experts
• We will cover the most widely – used patterns from the book
• 23 patterns in total – our unit will focus on 11
• GoF Design Patterns→Design Patterns as short
The University of 7
Design Patterns – Classification based on purpose
Scope
Creational
Structural
Behavioural
Class
Factory Method
Adapter (class)
Interpreter Template Method
Object
Abstract Factory Builder Prototype (object) Bridge Composite Decorator Façade Flyweight
Proxy
Chain of Responsibility Command
Iterator
Mediator
Memento Observer State Strategy Visitor
The University of 8
Design Patterns – Classification based on purpose
– Creationalpatterns
– Abstracttheinstantiationprocess
– Make a system independent of how its objects are created, composed and represented
– Structuralpatterns
– How classes and objects are composed to form larger structures
– Behavioralpatterns
– Concernswithalgorithmsandtheassignmentofresponsibilitiesbetween
objects
The University of 9
Design Patterns – Classification based on relationships
– Patternsoftenusedtogether
– E.g., Composite often used with Iterator or Visitor
– AlternativePatterns
– E.g.,PrototypeoftenalternativetoAbstractFactory
– Patterns results in similar designs
– E.g.,StructurediagramofCompositeandDecoratoraresimilar
The University of 10
Design Patterns – Classification based on relationships
Creational Pattern
Bridge
Proxy
Structural Pattern
Adapter
Behavioural Pattern
Mediator
Façade
State
sharing states
Flyweight
Strategy
Observer
Factory Method
Chain of Memento Reponsibility
often uses
Template Method
iterating
children
Iterator Composite
Command
Builder
Abstract Factory
Prototype
adding
operations
* Adapted from the GoF book: Design Patterns
The University of 11
Visitor
Interpreter
complex dependency management
single instance
saving state of iteration
defining the chain
sharing strategies
changing skin vs internals
adding responsibilities to objects
implement using
single instance
avoiding hysteresis
composed using
adding operations
creating composites
defining algorithm’s steps
defining traversals
defining grammar
configure factory dynamically
Selecting an Appropriate Design Pattern
It is useful to have some guidelines of how to select a pattern. Some thoughts on how you might do that:
– Consider the ways in which the design patterns solve problems. – Wewillgointodetailsonthisforseveraldesignpatterns
– Decide on what the intent of each design is.
– Withoutknowingwhatthemotivationofthedesignpatternis,itwillbe
hard to know whether it is right for you
– Look at the relationships among patterns
– It makes sense to use patterns that have a clear relationship, rather than one that you have manufacture ad hoc
The University of 12
Selecting an Appropriate Design Pattern
– Consider patterns with similar purpose
– Creational,StructuralandBehavioralarequitedifferentpurposesso
you should consider which one you need
– Look at why redesign might be necessary
– Knowing why a redesign might be needed will help you select the right design to avoid having to redesign later
– What can vary?
– Yourdesignshouldbeopentovariationwherenecessary
– Choose a design that will not lock you into a particular one, and enable you to make variations without changing your design
The University of 13
Design Aspects Can be Varied by Design Patterns
Purpose
Pattern
Aspects that can change
Creational
Abstract Factory Builder
Factory Method Prototype Singleton
Families of product objects
How a composite object gets created Subclass of object that is instantiated Class of object that is instantiated The sole instance of a class
Structural
Adapter Bridge Composite Decorator Façade Flyweight Proxy
Interface to an object
Implementation of an object
Structure and composition of an object Responsibilities of an object without subclassing Interface to a subsystem
Storage costs of objects
How an object is accessed; its location
The University of 14
Design Aspects Can be Varied by Design Patterns
Purpose
Pattern
Aspects that can change
Behaviour al
Chain of Responsibility Command
Interpreter
Iterator
Mediator Memento Observer
State
Strategy Template Method Visitor
object that can fulfill a request
when and how a request is fulfilled
grammar and interpretation of a language
how an aggregate’s elements are accessed, traversed
how and which objects interact with each other
what private info. is stored outside an object, & when number of objects that depend on another object; how the dependent objects stay up to date
states of an object
an algorithm
steps of an algorithm
operations that can be applied to object(s) without changing their class(es)
The University of 15
Creational Patterns
The University of 16
Creational Patterns
– Abstract the instantiation process
– Make a system independent of how its objects are created, composed and
represented
– Class creational patterns use inheritance to vary the class that’s instantiated
– Object creational pattern delegates instantiation to another object
– Provides flexibility in what gets created, who creates it, how it gets created and when
The University of 17
Creational Patterns
Pattern Name
Description
Abstract Factory
Provide an interface for creating families of related or dependent objects without specifying their concrete classes
a class only has one instance, and provide global point of access to it
Factory Method
Define an interface for creating an object, but let sub-class decide which class to instantiate (class instantiation deferred to subclasses)
Builder
Separate the construction of a complex object from its representation so that the same construction process can create different representations
Prototype
Specify the kinds of objects to create using a prototype instance, and create new objects by copying this prototype
The University of 18
Factory Method
Class Creational Pattern
An interface for creating an object
The University of 19
Factory Method Pattern
– Purpose/Intent
– Define an interface for creating an object, but let subclasses decide which class
to instantiate. Let a class defer instantiation to subclasses – Also known as
– Virtual Constructor – Motivated Scenario
– Suppose you have a general application framework (like Office) that can create a variety of different applications and document types. To create a spreadsheet applications, we might define SpreadsheetApp and SpreadsheetDoc; for a word processing application we’d have WordProcApp and WordProcDoc. Both use the common framework.
The University of 20
Factory Method Pattern
– Applicability
– A class cannot anticipate the class objects it must create
– A class wants its subclasses to specify the objects it creates
– Classesdelegateresponsibilitytooneofseveralhelpersubclasses,and you want to localise the knowledge of which helper subclass is the delegate
– Benefits
– Flexibility: subclasses get a hook for providing an extension to an
object; connects parallel class hierarchies – Limitations
– Canrequiresubclassingjusttogetanimplementation The University of 21
Factory Method Structure
The University of 22
Factory Method Participants
– Product
– Defines the interface of objects the factory method creates
– ConcreteProduct
– Implements the Product interface
– Creator
– Declares the factory method, which returns an object of type Product.
– ConcreteCreator
– Overrides the factory method to return an instance of the ConcreteProduct
The University of 23
Two varieties of Factory Method
– Variety 1: the Creator class is abstract
– Thisrequiressubclassestobemadebecausethereisnoreasonable
default value.
– On plus side, this avoids the problem of dealing with instantiating unforeseeable classes
– Variety 2: the Creator class is concrete
– Creatormayalsodefineadefaultimplementationofthefactory
method that returns a default ConcreteProduct object
– Thisprovidesreasonabledefaultbehaviors,andenablessubclassesto
override the default behaviors where required
The University of 24
Example
ShapeFactory sf = new RectangleFactory( ); Shape x = sf.createShape( );
The University of 25
Two varieties of Factory Method use
– Variety 1: only one Factory Method implementation is needed
– Existingcode,suchasalibrary,thatispassedaFactoryMethod
implementation at runtime.
– OnlyonetypeofProductisneededforthelifetimeoftheclient
– Variety 2: many Factory Method implementations are needed – ManytypesofProductsareneededatanytime
– Something needs to select which type of Product to produce.
• Something needs to ‘store’ the Factory Method implementation
The University of 26
Selecting a Factory Method source
– ‘Simple Factory’
Product makeProduct(Identifier identifier) { if (identifier.equals(…) {
return new ProductA();
} else if (identifier.equals(…) { return new ProductB();
} else if …
}
The University of 27
Selecting a Factory Method source
– Factory Registry
– Inessence,amappingfromidentifiertoimplementation
private Map
public void registerFactory(Factory factory, Identifier identifier); public Factory getFactory(Identifier identifier);
The University of 28
Builder
Object Creational Pattern
The University of 29
Builder
– Purpose/Intent
– Separatetheconstructionofacomplexobjectfromitsrepresentationso
that the same construction process can create different representations – MotivatedScenario
– Youhavearangeofimplementationsthatmightexpand,somustbe flexible, or you want to create instances of complex objects
– Applicability
– Thealgorithmforcreatingacomplexobjectshouldbeindependentof
the parts that make up the object and how they’re assembled
– The construction process must allow different representations for the object that’s constructed
The University of 30
Builder
– Benefits
– Gives flexibility that can be extended by implementing new subclasses
of the Builder, and isolates code of construction from implementation – Limitations
– Not completely generic, less useful in situations where variety of implementations is not high
The University of 31
Builder — Structure
The University of 32
Builder – Participants
– Builder
– Specifies an abstract interface for creating parts of a Product object
– ConcreteBuilder
– Constructsandassemblespartsoftheproductbyimplementingthe
Builder interface
– Defines and keeps track of the representation it creates.
– Providesaninterface(GetResult)forretrievingtheproduct
The University of 33
Builder – Participants
– Director
– Constructs an object using the Builder interface
– Product
– Represents the complex object under construction.
– ConcreteBuilder builds the product’s internal representation and defines the process by which it’s assembled
– Includes classes that define the constituent parts, including interfaces for assembling the parts into the final result
The University of 34
Builder – Rich Text Format Example
– A reader for the RTF (Rich Text Form) document exchange e format should be able to convert RTF to many text formats
– Problem: the number of possible conversions is open-ended, so it should be easy to add a new conversion without modifying the reader
– A solution is to configure the RTFReader class with a TextConverter object that converts RTF to another textual representation
– Subclasses of TextConverter specialise in different conversions and formats
– Each kind of converter class takes the mechanism for creating and
assembling a complex object and puts it behind an abstract interface
The University of 35
Builder – Rich Text Format Example
The University of 36
Builder – Rich Text Format Example
– Builder Pattern captures all the relationships
– Each converter class is called a builder in the pattern, and the reader is
called the director
– Itseparatesthealgorithmforinterpretingatextualformatfromhowa converted format gets created and represented
– The RTFReader’s parsing algorithm can be reused to create different text representations from RTFdocuments – just configure the RTFReader with different subclasses of TextConverter
The University of 37
Builder – Collaboration
The University of 38
Director d = new Director( );
Builder b = new ConcreteBuilder1( ); d.construct(b);
Product p = b.GetResult( );
Builder – Consequences (1)
– Varying product’s internal representation
– Because the product is constructed through an abstract interface, all you need to do to change the product’s internal representation is define a new kind of builder
– Isolation of code construction and representation
– Each ConcreteBuilder contains all the code to create and assemble a particular
kind of product.
– Different Directors can reuse it to build Product variants from the same set of parts
• E.g., SGMLReader uses the same TextConverters to generate different formats (ASCIIText, TextWidget and TexXText)
The University of 39
Builder – Consequences (2)
– Finer control over the construction process
– The builder pattern constructs the product step by step under the director’s
control
– Only when the product finished does the director retrieve it from the builder
– The builder interface reflects the process of constructing the product more than other creational patterns
The University of 40
Java Builder
– Related to, but not the same as GoF Builder
– Avoids issues with multiple complex constructors
– Provides default values for parameters of a complex object
– Parameters may be changed as needed
– A build() method creates the object – now only one constructor is needed
The University of 41
References
– , , , and .
1995. Design Patterns: Elements of Reusable Object-Oriented Software. Addison- Publishing Co., Inc., Boston, MA, USA.
– . 2004. Applying UML and Patterns: An Introduction to Object- Oriented Analysis and Design and Iterative Development (3rd Edition). PTR, Upper Saddle River, NJ, USA.
The University of 42