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

Lesson 6 - Design Patterns (1)

The document discusses design patterns in software engineering, defining them as reusable solutions to common problems in specific contexts. It outlines the history, properties, and types of design patterns, including creational, structural, and behavioral patterns, along with examples such as Singleton, Observer, and Adapter patterns. The document emphasizes the importance of design patterns in facilitating communication among developers and improving software architecture.

Uploaded by

dreamy
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

Lesson 6 - Design Patterns (1)

The document discusses design patterns in software engineering, defining them as reusable solutions to common problems in specific contexts. It outlines the history, properties, and types of design patterns, including creational, structural, and behavioral patterns, along with examples such as Singleton, Observer, and Adapter patterns. The document emphasizes the importance of design patterns in facilitating communication among developers and improving software architecture.

Uploaded by

dreamy
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 76

Advanced Software Engineering

Design Patterns
What is a Design Pattern?
• Is it an algorithm?

• Is it a design?

• What can you do with a design pattern?

• “Are all patterns design patterns?”

• What can you see in a design pattern?


Introduction
The recurring aspects of designs are called design patterns.

• A pattern is the outline of a reusable solution to a general


problem encountered in a particular context
• Many of them have been systematically documented for all
software developers to use
• A good pattern should
• Be as general as possible
• Contain a solution that has been proven to effectively solve
the problem in the indicated context.
Studying patterns is an effective way to learn from the experience
of others
Pattern origins and history
writings of architect Christopher Alexander
(coined this use of the term "pattern" ca. 1977-1979)

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


Gamma, Helm, Johnson, Vlissides ("Gang of Four“ - GoF)
Design Patterns: Elements of Reusable Object-Oriented Software, 1991-1994
PLoPD Conferences and books, 1994-present
Buschmann, Meunier, Rohnert, Sommerland, Stal, Pattern -Oriented Software
Architecture: A System of Patterns (“POSA book”)
Definitions

… 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]
...a literary format for capturing the wisdom and experience
of expert designers, and communicating it to novices
[Beck]
Properties
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
Properties (2)
• Patterns do not...
• provide an exact solution solve all design
problems
• only apply for object-oriented design
How patterns are seen
Perceived Understanding
Developers , Testers , (Can differ from person to
person)
End users
understands the
system differently
General design Guidelines
which are paradigm Specific

Solutions to recurrent designs


(Very Context Specific)
Mapping to
Pattern
Architectural
Patterns Architectural Principles

Design Patterns Design Principles

9
Ingredients
Pattern
Context
a design situation giving rise to a design problem
Problem
a set of forces occuring in that context
Solution
a form or rule that can be applied to resolve these forces
Example – Context: placing windows in a house
forces
• he wants to sit down and be comfortable
• he is drawn toward the light
solution
• in every room, make at least one window considering light
direction
Pattern description (Pattern template)
Context:
• The general situation in which the pattern applies
Problem:
• A short sentence or two raising the main difficulty.
Forces:
• The issues or concerns to consider when solving the problem
Solution:
• The recommended way to solve the problem in the given context.
—‘to balance the forces’
Antipatterns: (Optional)
• Solutions that are inferior or do not work in this context.
Related patterns: (Optional)
• Patterns that are similar to this pattern.
References:
• Who developed or inspired the pattern.
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 analysis models)


[Flower]

organization patterns (structure of organizations/projects)


process patterns (software process design)
domain-specific patterns
Types of Design Patterns
Creational Patterns
• to create objects of the right class for a problem,
generally when instances of several different classes
are available.
Structural Patterns
• to form larger structures from individual parts,
generally of different classes.
Behavioral Patterns
• to describe interactions between objects. They focus on
how objects communicate with each other.
Pattern Scope
Patterns can be further divided into two
categories
Object Patterns
• specify relationships between objects. In general, the
purpose of an object pattern is to allow the instances of
different classes to be used in the same place in a
pattern at runtime.
Class Patterns
• specify the relationship between classes and their
subclasses at compile time.
Design pattern catalog
Purpose

Creational Structural Behavioral

Class • Factory Method • Adapter • Interperter

• Abstract • Adapter • Chain of Responsibility


Factory • Bridge • Command
• Builder • Composite • Iterator
Scope • Prototype • Decorator • Mediator
Object • Singleton • Facade • Momento
• Flyweight • Observer
• Proxy • State
• Strategy
• Vistor
Creational GoF
• Abstract Factory
Creates an instance of several families of classes
• Builder
Separates object construction from its representation
• Factory Method
Creates an instance of several derived classes
• Object Pool
Avoid expensive acquisition and release of resources by
recycling objects that are no longer in use
• Prototype
A fully initialized instance to be copied or cloned
• Singleton
A class of which only a single instance can exist
Structural GoF
• Adapter
Match interfaces of different classes
• Bridge
Separates an object's interface from its implementation
• Composite
A tree structure of simple and composite objects
• Decorator
Add responsibilities to objects dynamically
• Façade
A single class that represents an entire subsystem
Structural GoF …
• Flyweight
A fine-grained instance used for efficient sharing
• Proxy
An object representing another object
Behavioral
• Chain of Responsibility
A way of passing a request between a chain of objects
• Command
Encapsulate a command request as an object
• Interpreter
A way to include language elements in a program
• Iterator
Sequentially access the elements of a collection
• Mediator
Defines simplified communication between classes
• Memento
Capture and restore an object's internal state
Behavioral
• Observer
• A way of notifying change to some classes
• State
• Alter an object's behavior when its state changes
• Strategy
• Encapsulates an algorithm inside a class
• Template method
• Defer the exact steps of an algorithm to a subclass
• Visitor
• Defines a new operation to a class without change
The Singleton Pattern
It is an object creational pattern.

The intent of the Singleton pattern is twofold:


• Guarantee that a class has only one instance
• Provide access to that instance
The Singleton Pattern
• Context:
• It is very common to find classes for which only one
instance should exist (singleton)
• Problem:
• How do you ensure that it is never possible to create
more than one instance of a singleton class?
• Forces:
• The use of a public constructor cannot guarantee that
no more than one instance will be created.
• The singleton instance must also be accessible to all
classes that require it
Singleton
• Solutpioubnl:ic class Singleton {
static Singleton theInstance
«Singleton»
= new Singleton();
theInstance

getInstance
private Singleton() { }
public static Singleton getInstance() {
return theInstance;
}
}
The Abstraction-Occurrence Pattern
• Context:
• Often in a domain model you find a set of related objects (occurrences).
• The members of such a set share common information
• but also differ from each other in important ways.
• Problem:
• What is the best way to represent such sets of occurrences in a
class diagram?
• Forces:
• You want to represent the members of each set of occurrences
without duplicating the common information
Abstraction-Occurrence
• Solution: «Abstraction» * «Occurrence»

TVSeries Episode
*
seriesName number
producer title
storySynopsis

Title LibraryItem
*
name barCodeNumber
author
isbn
publicationDate
libOfCongress
Abstraction-Occurrence
Antipatterns:
LibraryItem Title
LibraryItem
name name
name author author
author isbn isbn
isbn publicationDate publicationDate
publicationDate libOfCongress libOfCongress
libOfCongress barCodeNumber
barCodeNumber

LibraryItem
GulliversTravels MobyDick barCodeNumber
Abstraction-Occurrence
Abstraction-Occurrence Square variant
ScheduledTrain SpecificTrain
*
number date

* *
ScheduledLeg SpecificLeg
*
scheduledDepTime actualDepTime
scheduledArrTime actualArrTime
* *
origin destination
Station
The General Hierarchy Pattern
• Context:
• Objects in a hierarchy can have one or more objects above
them (superiors),
• and one or more objects below them (subordinates).
• Some objects cannot have any subordinates
• Problem:
• How do you represent a hierarchy of objects, in which some
objects cannot have subordinates?
• Forces:
• You want a flexible way of representing the hierarchy
• that prevents certain objects from having subordinates
• All the objects have many common properties and
operations
General Hierarchy
• Solution: «Node» *
«subordinate»

0..1
«NonSuperiorNode» «SuperiorNode»

FileSystemItem * contains
Employee * supervises

0..1 0..1

Secretary Technician Manager File Directory


General
Hierarchy
Antipattern:
Recording

VideoRecoding AudioRecording

MusicVideo JazzRecording ClassicalRecording BluesRecording RockRecording


The Player-Role Pattern
• Context:
• A role is a particular set of properties associated with
an object in a particular context.
• An object may play different roles in different contexts.
• Problem:
• How do you best model players and roles so that a
player can change roles or possess multiple roles?
Player-Role
• Forces:
• It is desirable to improve encapsulation by capturing
the information associated with each separate role in a
class.
• You want to avoid multiple inheritance.
• You cannot allow an instance to change class
• Solution: «Player» «AbstractRole»

«Role1» «Role2»
Player-Role
Example 1:
Animal 0..2 HabitatRole

typeOfFood habitat

Carnivore Herbivore Omnivore AquaticAnimal LandAnimal


Player-Role
Example 2:

AttendanceRole Student LevelRole

attendance level

FullTimeStudent PartTimeStudent GraduateStudent UndergraduateStudent


Player-Role
Antipatterns:

• Merge all the properties and behaviours into a


single «Player» class and not have «Role» classes
at all.
• Create roles as subclasses of the «Player» class.
The Observer Pattern
• Context:
• When an association is created between two classes,
the code for the classes becomes inseparable.
• If you want to reuse one class, then you also have to
reuse the other.
• Problem:
• How do you reduce the interconnection between
classes, especially between classes that belong to
different modules or subsystems?
• Forces:
• You want to maximize the flexibility of the system to
the greatest extent possible
Observer
«interface»
• Solution: «Observable» * *
«Observer»
addObserver
notifyObservers update

«ConcreteObservable» «ConcreteObserver»

* * «interface»
Observable
Observer

Observers are
notified when a new
Forecaster prediction is ready WeatherViewer
Observer
Antipatterns:
• Connect an observer directly to an observable so
that they both have references to each other.
• Make the observers subclasses of the observable.
The Delegation Pattern
• Context:
• You are designing a method in a class
• You realize that another class has a method which
provides the required service
• Inheritance is not appropriate
• E.g. because the isa rule does not apply
• Problem:
• How can you most effectively make use of a method
that already exists in the other class?
• Forces:
• You want to minimize development cost by reusing
methods
Delegation
• Solution:
delegatingMethod()
«Delegator» «Delegate» {
delegate.method();
delegatingMethod method }

push()
Stack LinkedList {
list.addFirst();
push addFirst }
pop addLast
isEmpty addAfter
removeFirst
removeLast
delete
isEmpty
Delegation
Example: two levels of delegation

Booking SpecificFlight * RegularFlight


**
flightNumber() flightNumber() flig htNumber()

flightNumber() flightNumber()
{ {
return return
specificFlight.flightNumber(); regularFlight.flightNumber();
} }
Delegation
Antipatterns
• Overuse generalization and inherit the method that is
to be reused
• Instead of creating a single method in the «Delegator»
that does nothing other than call a method in the
«Delegate
• consider having many different methods in the «Delegator»
call the delegate’s method
• Access non-neighboring classes
return specificFlight.regularFlight.flightNumber();

return getRegularFlight().flightNumber();
The Adapter Pattern
• Context:
• You are building an inheritance hierarchy and want to
incorporate it into an existing class.
• The reused class is also often already part of its own
inheritance hierarchy.
• Problem:
• How to obtain the power of polymorphism when reusing a
class whose methods
• have the same function
• but not the same signature
as the other methods in the hierarchy?
• Forces:
• You do not have access to multiple inheritance or you do not
want to use it.
Adapter Pattern - Usage
Adapter Pattern - Adapter

Cannot Connect

Can Connect
The adapter acts as a middleman by receiving requests
from the client and converting them into requests that
make sense to the vendor classes.
Adapter Pattern - Usage

» The Adapter Pattern should be used:


✓If you want to use an existing class, and its
interface does not match the one you need.

✓If you want to create a reusable class that


cooperates with unrelated or unforeseen classes,
that don’t necessarily have compatible interfaces.
Adapter
• Solution:
polymorphicMethod()
{
«Superclass» return
adaptee.adaptedMethod();
polymorphicMethod }

«Adapter» «Adaptee»
adaptedMethod
Adapter
Example: volume()
ThreeDShape {
return
volume TimsTorus.calcVolume();
}

Sphere Torus TimsTorus


calcVolume
Adapters
Other Names
Wrappers
Examples
Java Wrapper classes
Integer, Float, Double
Related Patterns
Façade, Read Only Interface, Proxy
The Façade Pattern - Context
General Issues
• A simple interface is required to access to a complex system.
• The abstractions and implementations of a subsystem are tightly
coupled.
• Need an entry point to each level of layered software.
• A system is very complex or difficult to understand because
system has a large
• number of interdependent classes or its source code is unavailable
Context:
• Often, an application contains several complex packages.
• A programmer working with such packages has to manipulate many different
classes
The Façade Pattern
• Problem:
• How do you simplify the view that
programmers have of a complex package?
• system is very complex with many classes
or difficult to understand because the
system has a large number of
interdependent classes or its source code
is unavailable to the client. A client needs a
simplified interface to the overall
functionality of this complex subsystem
Forces – Issues & Concerns
• It is hard for a programmer to understand and use an entire subsystem
• If several different application classes call methods of the complex package,
then any modifications made to the package will necessitate a complete
review of all
• Structuring a system into subsystems helps reduce complexity
• Shields clients from subsystem components there by reducing the number of
objects that clients deal with thus making the subsystem easier to use
• Promotes weak coupling between the subsystem and its clients Reduces
compilation dependencies in large software systems
• Does not prevent clients from using subsystem classes or their functionalities
directly if they need to be encapsulated these classes.
Solution
• The Facade Pattern provides a unified
interface to a set of interfaces in a subsystem.
Façade defines a higher-level interface that
makes the subsystem easier to use
Façade
• Solution:
«Facade» «PackageClass1»

«PackageClass2»

«PackageClass3»

* RegularFlight
Airline
findFlight
makeBooking *
deleteBooking Reservation
The Immutable
Pattern
• Context:
• An immutable object is an object that has a
state that never changes after creation
• Problem:
• How do you create a class whose instances are
immutable?
• Forces:
• There must be no loopholes that would allow
‘illegal’ modification of an immutable object
The Immutable Pattern
• Solution:
• Ensure that the constructor of the immutable
class is the only place where the values of
instance variables are set or modified.
• Instance methods which access properties
must not have side effects.
• If a method that would otherwise modify an
instance variable is required, then it has to
return a new instance of the class.
The Read-only Interface
Pattern
• Context:
• You sometimes want certain privileged classes to be able to
modify attributes of objects that are otherwise immutable
• Problem:
• How do you create a situation where some classes see a class
as read-only whereas others are able to make modifications?
• Forces:
• Restricting access by using the public, protected and
private keywords is not adequately selective.
• Making access public makes it public for both reading and
writing
Read-only Interface
• Solution:
«interface»
«ReadOnlyInterface» * «UnprivilegedClass»
getAttribute

«Mutable»
* «Mutator»
attribute «private»
getAttribute
setAttribute
Read-only Interface
Example:
«interface»
Person
getName

Mutableperson
firstName
lastName
setFirstName
setLastName
getName
The Proxy Pattern
• Context:
• Often, it is time-consuming and complicated to create instances of a
class (heavyweight classes).
• There is a time delay and a complex mechanism involved in creating
the object in memory
• Problem:
• How to reduce the need to create instances of a heavyweight class?
• Forces:
• We want all the objects in a domain model to be available for
programs to use when they execute a system’s various
responsibilities.
• It is also important for many objects to persist from run to run of the
same program
Proxy
• Solution:
«interface»
«ClassIF»

* * «Proxy» «HeavyWeight»
«Client»
Proxy
Example: «interface»
ListIF
The list elements will
be loaded into local
memory only when
needed.

ListProxy PersistentList

«interface»
Student

StudentProxy PersistentStudent
Factory Method
Case 1
• A button class has different
variations,(ImageButton, InputButton and
FlashButton).
• Depending on the request, it creates different
buttons.
Case 2
• There is a programme which draws a circle,
rectangle or square depending on the user input
• Problem
How do we encapsulate the object creational procedure that
may span different classes into one single function?
Forces
• Define an interface for creating an object and let the
subclasses to decide which class instantiates.
• Remember there isn't necessary to define factory
method if the class that's instantiated never changes,
or instantiation takes place in an operation that
subclasses can easily override scenarios.
Solution
• It encapsulates the knowledge of which product
subclass to create and moves this knowledge
out of the framework.
Factory Method Pattern

Define an interface for creating an object, and allow the subclasses to


decide which class to instantiate.

Factory Method lets a class defer instantiation to subclasses.


Factory Method
• http://sourcemaking.com/design_patterns/fac
tory_method

• http://en.wikipedia.org/wiki/Factory_method
_pattern
Difficulties and Risks When Creating Class
Diagrams
• Patterns are not a panacea:
• Whenever you see an indication that a pattern should
be applied, you might be tempted to blindly apply the
pattern. However this can lead to unwise design
decisions .
• Resolution:
• Always understand in depth the forces that need to be
balanced, and when other patterns better balance the
forces.
• Make sure you justify each design decision carefully.
Difficulties and Risks When Creating Class
Diagrams
• Developing patterns is hard
• Writing a good pattern takes considerable work.
• A poor pattern can be hard to apply correctly
• Resolution:
• Do not write patterns for others to use until you have considerable
experience both in software design and in the use of patterns.
• Take an in-depth course on patterns.
• Iteratively refine your patterns, and have them peer
• reviewed at each iteration.

You might also like