0% found this document useful (0 votes)
6 views117 pages

L10 11-ObjectInteractionDesignPatterns

The document outlines the principles and patterns of software engineering, particularly focusing on design patterns as reusable solutions to common problems in software design. It introduces the 'Gang of Four' (GoF) and categorizes their 23 design patterns into Creational, Structural, and Behavioral types. The document emphasizes the importance of design patterns in enhancing communication, creating maintainable software, and following object-oriented design principles.

Uploaded by

troyben91
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views117 pages

L10 11-ObjectInteractionDesignPatterns

The document outlines the principles and patterns of software engineering, particularly focusing on design patterns as reusable solutions to common problems in software design. It introduces the 'Gang of Four' (GoF) and categorizes their 23 design patterns into Creational, Structural, and Behavioral types. The document emphasizes the importance of design patterns in enhancing communication, creating maintainable software, and following object-oriented design principles.

Uploaded by

troyben91
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

CS3219: Software Engineering Principles and Patterns

Object Interaction Design Patterns


Design Patterns and O-O design reinforce each other.

CS3219 SEM1 AY2022/23 1


References: for the Lecture content
Links:

Examples:

[Link]
3219-SE-Principles-
and-
Patterns/Design_Patte
rns
(file uploaded in Readings
folder) Book GoF* – Source and
L10_L11-AdditionalNotes- Chapters 3,4,5 explanations
ObjectInteractionPatterns
Pages :97-, 117-, 139-,
Book POSA4 – Chapter 17 185-, 273-, 283-,
Pages : 400, 405-407, 410- 293-, 305-, 315-
411, 414-415, 418-419
* GoF - “Gang of Four” refers to the four authors of the book – Erich
2
Gamma, Richard Helm, Ralph Johnson, and John Vlissides.
Other References

Another good introductory


reference

CANVASàWeblinks
//OTOT Z1 from last year – just some samples

Liaw Siew Yee (Observer)


Chia Wei Hao, David (Observer)
Wen JunHua (Strategy)
Darien Chong Yung Han(Factory)
3
Lecture outline
Design patterns: some background

• What is a Design pattern


• Why do we learn about them
• How is a pattern specified
• Origin of design patterns
• GoF patterns Categories - Creational, Structural and Behavioral patterns
• GoF on creating good designs – some principles

Selected Patterns

• GoF Creational patterns : Builder, Prototype


• GoF Structural patterns : Adapter, Facade
• GoF Behavioral patterns : Observer, Mediator, Memento, State, Strategy
• Other(non GoF) patterns: DTO

CS3219 SEM1 AY2022/23 4


Lecture outline

Design patterns: some background

• What is a Design pattern


• Why do we learn about them
• How is a pattern specified
• Origin of design patterns
• GoF patterns Categories - Creational, Structural and Behavioral patterns
• GoF on creating good designs – some principles

Selected Patterns

• GoF Creational patterns : Builder, Prototype


• GoF Structural patterns : Adapter, Facade
• GoF Behavioral patterns : Observer, Mediator, Memento, State, Strategy
• Other(non GoF) patterns: DTO

CS3219 SEM1 AY2022/23 5


History of patterns Patterns -
background

What is present in a good quality design that is


not present in the poor quality design?

and

What is present in a poor quality design that is


not present in the good quality design?

Author: Christopher Alexander


A “pattern language” for
designing the urban
environment.

SEM1 AY2022/23 Source: Chapter 5 Design Patterns Explained by Shalloway & Trott 6
From Architectural to Software Design patterns Patterns -
background

Authors: Erich Gamma, John Vlissides,


Ralph Johnson, and Richard Helm.

Were there problems in software that occur


over and over again that could be solved in
somewhat the same manner?

Was it possible to design software in terms of


patterns, creating specific solutions based on
these patterns only after the patterns had
been identified?

“the Gang of Four(GoF) book” features patterns solving various problems of o-o design.

7
Patterns -
The GoF Design Patterns background

• The book described a structure within which to catalog and


describe design patterns
• It cataloged 23 design patterns.
• Authors did not create the patterns described in the book.
They identified patterns already existing within the software
community.

CS3219 SEM1 AY2022/23 8


What is a Design Pattern Patterns -
background

Design pattern : A solution to a problem in a context.

The context is the The problem is the goal The solution is the
situation in which the to be achieved in the pattern
pattern applies context. This includes any • A general design that
• The situation should constraints that apply can be applied to
be recurring • Goal and constraints problems in this context
are referred to as • It achieves the goal while
forces satisfying the constraints

CS3219 SEM1 AY2022/23 9


Why should we learn about Design patterns? Patterns -
background

• A toolkit of tried and tested solutions to common problems in


software design.

• A shared vocabulary/ common language that you and your


teammates can use to communicate more efficiently.

CS3219 SEM1 AY2022/23 10


What does the pattern consist of? Patterns -
background

Name Every pattern must have a name so that it can be referenced


Classification This is a means of categorizing patterns
Intent What the pattern does - it's definition
Participants Classes and objects involved in the pattern
The responsibilities of each participant
Implementation/ Techniques to use in implementing the pattern
Sample code Issues to be aware of when implementing

CS3219 SEM1 AY2022/23 11


FYI: A more elaborate Design Pattern Template Patterns -
background

Name Every pattern must have a name so that it can be referenced


Classification This is a means of categorizing patterns
Intent What the pattern does - it's definition
Motivation Why the pattern is used
Applicability Situation to which the pattern is applied
Participants Classes and objects involved in the pattern
The responsibilities of each participant
Collaborations How participants work together to achieve the task
Consequences Positive effects of using the pattern
Negative effects of using the pattern
Implementation/ Techniques to use in implementing the pattern
Sample code Issues to be aware of when implementing
Known uses Examples of the pattern as used in real systems
Related
CS3219 SEM1patterns
AY2022/23 How the given pattern relates or compare to others 12
GoF Patterns categories GoF patterns -
overview

Creational Patterns
• Creational patterns help designers handling issues
with creation of objects.
• e.g. Factory pattern
Structural Patterns
• Structural Patterns are used to provide a structure to
the relationship between objects.
• e.g. Façade pattern
Behavioral Patterns
• Behavioral Patterns help define how objects interact
with each other to deliver a task.
• e.g. Observer pattern

CS3219 SEM1 AY2022/23 13


GoF Patterns categories GoF patterns -
overview

Source : [Link]
14
GoF patterns -
overview

Source : [Link]
15
GoF patterns -
overview

Source : [Link] 16
GoF patterns – an overview GoF patterns -
overview

Creational Structural

Reference : [Link]
Link also has example codes in C++ and Java
Behavioural
CS3219 SEM1 AY2022/23 17
Creational patterns GoF patterns -
overview

• These patterns provide ways to instantiate single objects or


groups of related objects.
- their purpose is to encapsulate/hide details about the actual creation

Factory

Prototype Singleton

Abstract
Factory

Builder

CS3219 SEM1 AY2022/23 18


Structural patterns GoF patterns -
overview

• Structural patterns provide a manner to define


relationships between classes or objects in order to
form larger structures.
- they define how these components should be Adapter
structured so that there is flexiblility in
Decorator
interconnecting modules Composite

Proxy Façade

Flyweight Bridge

CS3219 SEM1 AY2022/23 19


Behavioural patterns GoF patterns -
overview

Behavioural patterns define manners of communication


between classes and objects.
- Their purpose is to increase communication flexibility between objects based on
the specific ways they interact with each other.
- They offer to simplify this flow and make it more understandable.

Chain of
Responsibility

Template Command Mediator Interpreter


Observer

Strategy Memento State Visitor


Iterator

CS3219 SEM1 AY2022/23 20


GoF patterns -
GoF on creating good O-O designs overview

more principles….

• Program to interface
• Favor composition(or aggregation) over inheritance
- Prefer has-a over is-a
• Encapsulate what ‘varies’
– Separate what ‘varies’ from what ‘does not vary’ or from another thing
that ‘varies’

CS3219 SEM1 AY2022/23 21


Program to Interface (P2I) GoF patterns -
overview

[Erich Gamma, GoF, Design patterns ]

“This principle is really about dependency relationships which have to be


carefully managed in a large app.

…..Once you depend on interfaces only, you’re decoupled from the


implementation. That means the implementation can vary, and that’s a healthy
dependency relationship.

…. An abstract class is good as well. …

Ref: GoF book, page 17-18

Eric Gamma’s thoughts on ‘P2I’ & ‘composition over


inheritance’ 22
Favor composition over inheritance GoF patterns -
overview

[Erich Gamma, GoF, Design patterns ]


“ Inheritance is a cool way to change behavior. But …… there's a tight coupling
between the base class and the subclass.…”

“Composition has a nicer property. The coupling is reduced by just having some
smaller things you plug into something bigger, and the bigger object just calls the
smaller object back…….”

Eric Gamma’s thoughts on ‘P2I’ & ‘composition over inheritance’

This design principle essentially suggests us that “has-a relationship should be


preferred over is-a relationship”.

23
GoF patterns -
overview

Example: Design a

• All operations take place at the “ ” of the stack.


• The “ ” operation adds an item or a collection of items to
the top of the stack.
• The “ ” operation removes an item on the top of the stack
and returns it.

24
Stack Version 1 (is-A)

25
GoF patterns -
overview

Version 1 design : Stack an ArrayList

Stack features from


ArrayList.

Override Undesirable Methods


and Throw an They are Undesirable!
to deal with them at all?
i.e. ?

principle
Favor over
Inheritance 26
GoF patterns -
overview

Stack Version2 (has-A)


Favor composition over inheritance

B Wadhwa - CS3219 SEM1 AY2020/21 27


GoF patterns -
Encapsulate (& separate) what ‘varies’ overview

If a component or module in your application is bound to change frequently, then it’s a good
practice to separate this part of code from the rest(that does not vary) so that later we can
extend or alter the part that varies without affecting those that don’t vary.

public void processServiceRequest(String serviceType)


{ OnlineService service;

if([Link]("AirConditioner")) service = new ACService(); else


if([Link]("WashingMachine")) service = new WMService(); else
if([Link]("Refrigerator")) service = new RFService(); else
service = new GeneralService();

[Link]();
[Link]();
[Link]();
[Link]();}

CS3219 SEM1 AY2022/23 28


public void processServiceRequest(
GoF patterns -
String serviceType) {
overview
OnlineService service = new public class OnlineServiceFactory {
OnlineServiceFactory().getOnlineService
(serviceType); public OnlineService
getOnlineService(String type) {
[Link]();
[Link]();
[Link]();
OnlineService service;
[Link]();
if([Link]("AirConditioner")
} ) service = new ACService(); else

if([Link]("WashingMachine")
) service = new WMService(); else

if([Link]("Refrigerator"))
service = new RFService(); else
service = new GeneralService();

return service;
FYI: This example illustrates another
}
principle of separating ‘creation’ from ‘use’ } 29
Example Source: Chapter 10 Design Patterns Explained by Shalloway & Trott GoF patterns -
[Link] overview

Context: Drawing a rectangle with either of the two drawing


programs DP1 or DP2.

DP1 : draw_a_line(x1,y1,x2,y2)
DP2: drawline(x1,x2,y1,y2)

Design Ver 1:

30
• Support another kind of shape—a circle.
• Client need not know the difference between Rectangles and
Circles.
Design Ver 2:
DP1 : draw_a_line(x1,y1,x2,y2)
draw_a_circle( x, y, r)

DP2: drawline(x1,x2,y1,y2)
drawcircle( x, y, r)

CS3219 SEM1 AY2022/23 An alternative design 31


Four specific types of Shapes here à
Another variation in implementation will
have more kinds of Shapes.
à The class explosion problem

The abstraction (the kinds of Shapes) and


the implementation (the drawing programs)
are coupled.
Each type of shape must know what type of
drawing program it is using.
Other issues: there appear to be some
redundancy and low cohesion.

Could we identify(& separate) what is ‘varying’


-- the variations in shapes
-- the variations in drawing programs
32
GoF patterns -
overview

Separate Shapes from drawing programs.


Shape to encapsulate the concept of the types of shapes.
Drawing objects, on the other hand, are responsible for
drawing lines and circles.

Separate the variations in abstraction from the variations in implementation

CS3219 SEM1 AY2022/23 33


GoF patterns -
overview

Design Ver 3:

Bridge pattern:

FYI: Why not Drawing uses Shape? and the code sample
[Link]

FYI:
CS3219 SEM1 AY2022/23 [Link]
Summary so far…. GoF patterns -
overview
• A design pattern is a reusable solution to a recurring problem in software design.

• It is not a finished piece of code but a template that helps to solve a particular problem or family of problems.
– You can’t paste it into your program like a library because it is not a specific piece of code.
– They are high-level descriptions of a solution that are meant to provide a guidance on structure, relations and
hierarchy of an object as well as classes and interfaces in the application.

• Four authors, Erich Gamma, Richard Helm, Ralph Johnson and John Vlissides, initiated the concept of Design Pattern in
Software development.
– These authors are collectively known as Gang of Four(GoF)
– GoF 23 patterns are categorised in 3 categories – Creational, Structural, Behavioral

• Patterns are extremely valuable


– They give us a vocabulary
– And a way of thinking and communicating about software
– Patterns follow design principles therefore they help us build reusable, extensible and maintainable software regardless of the
programming language you use or application we are building.
– They helps us learn and use new frameworks faster because these design patterns are ubiquitous in the coding world.
• Do not be surprised if a new library you are learning looks familiar (perhaps with different syntax) as a result of this knowledge.

• GoF patterns follow some of the O-O fundamentals including concepts of encapsulation, abstraction, polymorphism,
inheritance and composition, many deisgn principles including SOLID principles and principles of Program to Interface,
Favor Composition over Abstraction and Encapsulate(& Separate) what ‘varies’
CS3219 SEM1 AY2022/23 35
Lecture outline

Design patterns: some background

• What is a Design pattern


• Why do we learn about them
• How is a pattern specified
• Origin of design patterns
• GoF patterns Categories - Creational, Structural and Behavioral patterns
• GoF on creating good designs – some principles

Selected Patterns

• GoF Creational patterns : Builder, Prototype


• GoF Structural patterns : Adapter, Facade
• GoF Behavioral patterns : Observer, Mediator, Memento, State, Strategy
• Other(non GoF) patterns: DTO

CS3219 SEM1 AY2022/23 36


Selected GoF Patterns for this lecture Selected Patterns
for the Lecture

non-GoF /
Creational Structural Behavioral
others

Data Transfer
Builder Adapter Mediator
Object

Prototype Façade Memento

Bridge
Observer
(Ref slides in earlier
section -GoF on
creating good design)

State

Strategy

CS3219 SEM1 AY2022/23 37


Creational Patterns
Builder

Builder
A creational pattern
The creational design patterns deal with object creation mechanisms.

The main ideas behind the creational design patterns is:


-Knowledge encapsulation about the concrete classes /
actual creation

The builder design pattern is useful for objects with many possible
constructor parameters that would otherwise require developers to create
many overrides for the different scenarios an object could be created in.

Many of the modern libraries today employ this design pattern.

CS3219 SEM1 AY2022/23 38


Creational Patterns
Example – House Builder Builder

CS3219 SEM1 AY2022/23 39


Creational Patterns
Example – House Builder Builder

CS3219 SEM1 AY2022/23 40


Creational Patterns
Example – House Builder Builder

Basic house

Additional Representation

CS3219 SEM1 AY2022/23 41


Creational Patterns
Example – House Builder Builder

Build process of the house – foundation, Representation of House – concrete house,


structure, roof, paint, furnish Tree house , or Igloo

Construction Engineer (Director) Builder (Specialist Builder)

CS3219 SEM1 AY2022/23 42


Creational Patterns
Example – House Builder Builder

Build process of the house – foundation, Representation of House – concrete house,


structure, roof, paint, furnish Tree house , or Igloo

43
Creational Patterns
Example – House Builder Builder

House Building is a step-by-step process


- that includes the steps to create the foundation, structure, and roof followed by the
steps to paint and furnish a house and these steps remain the same irrespective of the
type of house to build.

- & the finished product, which is a house, can have different representations – i.e. it can
be a concrete house, a prefabricated house, or a tree house.
A Construction
Engineer(Director)
A House(Product)
directs a builder to
represents the product to
perform the steps in the
create.
order that is required to
build the product.

A SpecialistBuilder(Builder )
knows how to build the parts of a product.
Specific types of Builders e.g.
ConcreteHouseBuilder and PrefabricatedHouseBuilder
construct and assemble parts of the product and return the finished
product.
44
Builder pattern Creational Patterns
Builder

Intent: Separate the construction of a complex object from its


representation so that the same construction process can create
different representations.

• The builder pattern enforces a step-by-step process to


construct a complex object as a finished product.

• In this pattern, the step-by-step construction process remains


same but the finished products can have different
representations.
CS3219 SEM1 AY2022/23 45
Participants in the Builder pattern Creational Patterns
Builder

Product : A class that represents the product to create.

Director : A class that directs a Builder to perform the steps in the


order that is required to build the Product.

Builder : An interface to build the parts of a product.

ConcreteBuilder: concrete classes that implements Builder to


construct and assemble parts of the product and return the
finished product.
A client is insulated from the object creation process. A client only needs to provide the
Director a ConcreteBuilder to use. It is the responsibility of the Director to instruct the
ConcreteBuilder on the construction process and the ConcreteBuilder in turn will create the
finished product. Finally, the client receives the finished product from the Director.
46
Participants in the Builder pattern Creational Patterns
Builder

Ref: GoF page 98

CS3219 SEM1 AY2022/23 47


Creational Patterns
Builder

“Separate the construction of a complex object from its Ref: GoF page 99
representation so that the same construction process
can create different representations.” 48
FYI: more links for Builder pattern Creational Patterns
Builder

“The Builder pattern is a good choice when designing


classes whose constructors or static factories would
have more than a handful of parameters, especially if
many of the parameters are optional or of identical
type"
Also in many libraries eg

[Link]
Effective Java, Joshua Bloch /util/[Link]

[Link] [Link]
/util/[Link]
[Link]
Another article:
Bloch is currently an affiliated faculty [Link]
member of the Institute for Software four/builder/
Research at Carnegie Mellon University,

CS3219 SEM1 AY2022/23 49


Creational Patterns
Prototype

Prototype

This design pattern allows object creation from an already created instance.
It can be used in cases when a specific resource is expensive to create.

CS3219 SEM1 AY2022/23 50


Creational Patterns
Example Prototype

Consider a content production house CPH


It employs vendors to write content.

For each project assigned to a vendor, the HR department provides


the vendor a terms and conditions T&C and a non-disclosure CPH
agreement NDA

The content of the agreements remains same for all vendors


HR employee only needs to fill in the vendor name before sending an
agreement to the vendor.
Vendor
Assuming that the agreement content are stored in a remote database,
HR employee could make local copies to avoid making a network trip and
a database read each time the employee needs to create an agreement.

51
Prototype pattern Creational Patterns
Prototype

• Intent: create an object by cloning another as necessary

• With Prototype, you do not create a new object for each


client requesting the object.

• Instead, you start by creating a single object, called a


prototype and then make copies of it for each client
requesting the object.
– In Java, this is achieved through object cloning, a way to make a
copy of an object with the same state as the original object.

CS3219 SEM1 AY2022/23 52


Creational Patterns
Typical Object creation : Prototype

CS3219 SEM1 AY2022/23 53


Creational Patterns
Prototype

In prototype pattern :
- the Client class doesn't instantiate the Product1 object directly.
- Instead, the Client refers to the Prototype interface for cloning an object.
- The Product1 class implements the Prototype interface by creating a copy of itself.
The Sequence Diagram shows the run-time interactions:
- The Client object calls clone() on a prototype:Product1 object, which creates and returns a
54
copy of itself (a product:Product1 object).
public class MyApp { Creational Patterns
public static void main(String[] args) { Prototype
// Creating a Client object
// and configuring it with a Prototype object.
Client client = new Client(new Product1("Product1"));
// Calling an operation on the client.
[Link]([Link]());
}
public class Client {
}
private Product product;
private Prototype prototype;
Client: Cloning Product1. public Client(Prototype prototype) {
Product1 object copied.
[Link] = prototype;
}
public String operation() {
product = [Link]();
return "Client: Cloning " +
[Link]().getName() +
".\n" + [Link]() + " object copied.";
}
CS3219 SEM1 AY2022/23 55
}
// Product1 implements both the Product and Prototype Creational interface.
Patterns
public class Product1 implements Product, Prototype { Prototype
private String name;
public Product1(String name) {
[Link] = name;
}
// Copy constructor needed by clone().
public Product1(Product1 p) {
[Link] = [Link]();
}
@Override
public Product clone() {
return new Product1(this);
}
public interface Product {
public String getName() {
String getName();
return name;
}
}
} public interface Prototype {
Product clone();
CS3219 SEM1 AY2022/23 } 56
Creational Patterns
Participants of the Prototype pattern Prototype

Client: asks the PrototypeManager** for copies of prototypes.

Prototype: a Java interface or abstract class that defines the contract for
classes that permits cloning of its objects.

ConcretePrototype : a class(es) that provides operations to clone its objects.

FYI: Sometimes you also find a class PrototypeManager in this pattern. On a


client request, this class creates a copy of a prototype. (It can be merged with
client class for a simple case.). This diagram does not show prototype manager .
PrototypeManager is useful in case of a complex application where several
prototype types need to be managed for the client.
When should we use it Creational Patterns
Prototype

• This pattern should be followed, if the cost of creating a new


object is expensive.

• In situations where construction of an object involves time


consuming operations, such as network communication,
database reads etc. and many many objects are to be created.
– Avoid repeating those steps for each object by initially
creating a prototype and then making copies of it.

CS3219 SEM1 AY2022/23 58


FYI: more links and information for Prototype pattern Creational Patterns
Prototype

• Example and explanation


[Link]

Another related concept is that of Object cloning : Deep and Shallow copy

CS3219 SEM1 AY2022/23 59


Creational Patterns
FYI: Object Cloning: Shallow Copy Vs Deep Copy Prototype

• Java Cloneable interface marks objects that permit cloning.


– This interface is a marker interface and therefore does not contain any
method declaration.
– When implemented in a class, marks that objects of the class can be cloned.
– To perform cloning, call the protected clone() method of the Object class
through a call to [Link]()
– A call to performs a shallow copy where all the fields values of the original
object are copied to the new object.
– But, if a field value is a reference type, then only the reference is copied, and
not the referred object itself.
– Therefore, both the original and its clone refer to the same object and if either
one modifies the referred object, the modification will be visible to the other.
• Unexpected behaviours
– In a deep copy, the original and the copied objects are independent of each
other and therefore the objects can update their own fields without worrying
about any referencing problems.
CS3219 SEM1 AY2022/23 60
Creational Patterns
FYI: Should we deep copy or shallow copy in Prototype ? Prototype

• If an object has only primitive fields or immutable objects


(whose state cannot change, once created), use a shallow
copy.

• When the object has references to other mutable objects,


then either choose shallow copy or deep copy.
– For example, if the references are not modified anytime,
avoid deep copy and go for shallow copy.
– But, if you know that the references will be modified and
the modification might affect the intended behavior of the
application, then you need to go for deep copy.
CS3219 SEM1 AY2022/23 61
Structural Patterns
Adapter

Adapter (a.k.a. Wrapper)

The adapter design pattern allows the interface of an existing class to be used from another interface.

CS3219 SEM1 AY2022/23 62


Adapter pattern (aka Wrapper) Structural Patterns
Adapter

Intent: Convert the interface of a class into another interface that clients
expect. Adapter lets classes work together that couldn’t otherwise because of
incompatible interfaces.

Image source: [Link]

When to use:
-- Imagine that there is a client who expects your class to expose a doTask () method.
You might have the implementation ready in another class, but the method is called differently and is
incompatible. It might require extra parameters too.
-- This could also be a library that the developer doesn’t have access to for modifications.
63
Structural Patterns
Participants of the Adapter pattern: Adapter

Client: Communicates with the Target.

Target : The existing interface that clients communicate with.


Adaptee : The new incompatible interface that needs adapting.
Adapter : A class that adapts the Adaptee to the Target.

Image source: [Link]

CS3219 SEM1 AY2022/23 64


The client can’t use Service class directly because it has an
incompatible interface.
The Service is some useful class (usually 3rd-party or legacy).

The Client Interface describes a protocol that other classes must


follow to be able to collaborate with the client code.

Object Adapter : The Adapter is a class that’s able to work with


both the client and the service: it implements the client interface,
while wrapping the service object.

The adapter receives calls from the client via the adapter interface
and translates them into calls to the wrapped service object in a
format it can understand.

Class Adapter: The Adapter inherits behaviors from both


the client and the service.
The adaptation happens within the overridden methods.
The resulting adapter can be used in place of an existing
client class.

Note that this approach can only be implemented in programming languages


that support multiple inheritance, such as C++.
FYI: more links and information Structural Patterns
Adapter

Example: [Link]

The Adapter pretends to be a round peg, with a radius equal to a


half of the square’s diameter (in other words, the radius of the
smallest circle that can accommodate the square peg).

[Link]

[Link]

CS3219 SEM1 AY2022/23 66


Structural Patterns
Facade

Façade (face of the building)


Simple and specific interface onto a group of objects.
“Provide a unified interface to a set of interfaces in a subsystem. Facade defines a
higher-level interface that makes the subsystem easier to use.”
[GoF]

CS3219 SEM1 AY2022/23


Louvre, Paris 67
Structural Patterns
Facade

CS3219 SEM1 AY2022/23 68


Façade pattern Structural Patterns
Facade

Intent: provide a simple unified interface to a set of interfaces in a


subsystem.
Façade : A unified interface that makes the subsystem(s) easier to use.
Clients interact with the facade instead of individual subsystem.
The facade handles the underlying interactions with the subsystem transparently
from the clients.

69
Structural Patterns
Participants of the Façade pattern: Facade

Client (not shown in this diagram):


Requests the facade to perform some
action.

Facade: Delegates client requests to


appropriate subsystem classes.

Subsystems (Package A/B in diagram):


Implement subsystem functionalities.
Subsystems are used by the facade, but not
the other way around. The subsystem
classes have no reference to the facade.

CS3219 SEM1 AY2022/23 70


Façade pattern Structural Patterns
Facade

“Provide a unified interface to a set of interfaces in a subsystem. Facade defines a


higher-level interface that makes the subsystem easier to use.”
[GoF]

Image source: [Link]

Db
Image source: [Link]
Product Data +Store(productionData) Application
+GetProduct(sku)
+DeleteProductData(sku)

[Link]

SqlConnection SqlCommand IDataReader


FYI: more links and information Structural Patterns
Facade

[Link]
A Facade class can often be transformed into a Singleton since a single facade object is sufficient in most cases.

[Link]

In Java, the interface JDBC can be called a facade because, we as users or clients create connection using the
“[Link]” interface, the implementation of which we are not concerned about.
The implementation is left to the vendor of driver.

[Link]

CS3219 SEM1 AY2022/23 72


Behavioral Patterns
Observer

Observer pattern
e.g. in Twitter application:
You follow a user and when that user tweets, you Smalltalk Model-View-Controller (MVC)
along with all other followers of that user receive
Pub/sub middleware (CORBA Notification
the tweet. Service, JMS)
The user account you are following is the publisher
and your twitter account along with the other Phone event frameworks (Android, iOS)
followers are the subscribers.
When you unfollow the user, you stop receiving
tweets of the user.

Image source: [Link]


73
Observer pattern Behavioral Patterns
Observer

Intent: Let objects observe the behavior of other objects so they


can stay in sync.
Context:
– an abstraction has two aspects
– one dependent on the other
– a change to one aspect requires notifying dependents

“Define a one-to-many dependency between objects so


that when one object changes state, all its dependents
are notified and updated automatically.”
[GoF]

[Link]
CS3219 SEM1 AY2022/23 74
Behavioral Patterns
Participants of the Observer pattern Observer

Subject – interface or abstract


class defining the operations for attaching
and de-attaching observers to the subject.
ConcreteSubject – concrete Subject class.
It maintain the state of the object and
when a change in the state occurs it
Relevant vocabulary :
notifies the attached Observers. Register/Attach: Observers register themselves to the
subject because they want to be notified when there
Observer – interface or abstract class is a change.
Event: Events act as a trigger in the subject such that
defining the operations to be used to all the observers are notified.
Notify: Depending on the implementation, the
notify this object. subject may “push” information to the observers, or,
the observers may “pull” if they need information
from the subject.
ConcreteObserver – concrete Observer Update: Observers update their state independently
from other observers however their state might
implementations. change depending on the triggered event.

CS3219 SEM1 AY2022/23 75


Observer pattern Behavioral Patterns
Observer

Benefits:
• observers offer different views of the
subject
• can easily add observers
Concerns:
• Registering modifications of interest
• eg De-register and register again
• Update protocols
• the push & pull models; filtering

CS3219 SEM1 AY2022/23 76


Observer pattern change propagation (aka notification-update) Behavioral Patterns
Observer

Fig Ref page 405 Chapter 17 - POSA

CS3219 SEM1 AY2022/23 77


Behavioral Patterns
Observer pattern pull & push models Observer

pull model push model

Subject changes state. It notifies all Subject changes state;


observers.
Observer calls back to the subject Subject pushes a snapshot of its
to retrieve more detailed state to all observers.
information.

Categorized Pull model Categorized push model


Observers to register with A small portion of state is
specific state changes. pushed to only those observers
who are interested in it.
CS3219 SEM1 AY2022/23 78
FYI: more links and information Behavioral Patterns
Observer

[Link]
You can use Unity Events or C# Delegates/Events or
Actions to implement it in your code

[Link]

- Don't have chains of objects observing other objects, observing other objects.
- Observers are best use across the layer boundary, the classic use is for presentations to observer the domain.

CS3219 SEM1 AY2022/23 79


Behavioral Patterns
Mediator

Mediator
“talk with me instead of talking among yourselves”.
Mediator pattern Behavioral Patterns
Mediator

“Define an object that encapsulates how a set of objects interact. Mediator promotes loose coupling by keeping
objects from referring to each other explicitly, and it lets you vary their interaction independently.” [GoF]

If an object is updated with new interaction rules or a new object is added only
the mediator object needs to updated.
81
Mediator pattern Behavioral Patterns
Mediator

Intent: Define an object that encapsulates how a set of objects interact,


to reduce coupling.

Mediator encapsulates how a set of objects


interact.

Objects delegate the routing of requests,


messages, data that they exchange with other
objects to the Mediator.

Mediator allows the loose coupling between


set of objects by handling the interactions
between the objects.
82
Mediator pattern Behavioral Patterns
Mediator

Ref page 410 Chapter 17 - POSA

CS3219 SEM1 AY2022/23 83


Participants of Mediator pattern Behavioral Patterns
Mediator

A typical object structure might look like this

Ref: GoF

CS3219 SEM1 AY2022/23 84


Behavioral Patterns
Participants of Mediator pattern Mediator

MediatorBase : an abstract class that declares methods for communicating


with Colleague objects.
ConcreteMediator : Implements Mediator.
This class maintains and coordinates Colleague objects.
ConcreteMediator holds references to the colleagues that it serves.
SendMessage is called by a colleague object when it wishes to transmit a
message, passing the caller object as a parameter.
The mediator then decides which of the colleagues should receive the
message and calls their Receive methods.
ColleagueBase: An abstract class for the colleague objects.
It defines a single, protected field that holds a reference to a mediator.
ConcreteColleague: The concrete colleagues communicate with each other
via the mediator.
The Send and Receive methods are used to send messages to and receive
85
messages from the mediator.
FYI: more links and information Behavioral Patterns
Mediator

[Link]

Example of the Mediator Pattern: Spring MVC uses the Dispatcher Servlet(Front
Controller) in conjunction with the controllers. The Front Controller acts as a
mediator between web request, the controller objects, and the view objects.

[Link]

Example: DOM
..Whenever we load a web page, the browser creates the Document Object Model (a tree like structure that represents every element of a web
page) of that page…… Any event emission, broadcasting or subscription happens via the document object itself. Instead of binding to the events of
the individual nodes, a higher-level object (Document) is given the responsibility of notifying subscribers about interaction events. The document
object mediates information among other elements (nodes) in a web page. …

CS3219 SEM1 AY2022/23 86


Behavioral Patterns
Memento

Memento
”allow client to capture an object’s state, and restore”

Example Use cases:


-allowing a gamer to undo a wrong move or
revert to an earlier level in a Game
-allowing undo for a desktop word processing
application
-allowing a user to revert back a checkout
process in an e-commerce application

87
Memento pattern Behavioral Patterns
Memento

Allows to capture an object’s internal state and save it externally so you can restore it later.
But, not at the expense of exposing Object’s internal state else it would violate encapsulation – a
key OOP concept.
Basic mechanism :
1. We have an object, called the Originator whose state (or even its partial state) needs to be saved.
2. So we will need another object, called the Memento which will hold different states of the Originator.
- The Memento class needs to have the same properties as the Originator in order to save the state.

3. But if the Originator has its properties as private fields, then they won’t be accessible outside the Originator.
- This means the no other object or Memento can access Originator’s private fields .

4. Therefore, the Originator object should :


•Create a Memento object with the current state of the Originator object.
- The object state is separated from the object (Originator) itself
•The Originator should update the Memento object whenever it’s state changes and it deems it necessary
to save the changed state.
7. How do we manage Memento(es)
- By introducing another object Caretaker : The safekeeper of Memento objects.
8. How do we Restore Originator’s previous state from a Memento object.
- When needed, Memento is returned to Originator by Caretaker
- Originator uses the Memento to restore back its state.
88
Behavioral Patterns
Memento pattern Memento

Intent: without violating encapsulation, allow client to capture an


object’s state, and restore

Originator : An object whose state (or even its


partial state) needs to be saved.

Memento : holds state of the Originator.

Caretaker : The safekeeper of Memento


objects.

Caretaker object does not modify the state of


Memento object.

[Link]
89
Participants of Memento pattern Behavioral Patterns
Memento

Originator Defines an operation createMemento() for saving its current internal


state to a Memento object.

Defines another operation restore(memento) for restoring to a


previous state from a passed in Memento object.

Memento Stores an originator's internal state.

Only the originator that created a memento can access it.

This is usually implemented by making memento an inner class of originator


and declaring all members of memento private.
Caretaker Refers to the Originator class to save and restore originator's
internal state.
Holds Memento objects, created and returned by the originator, and
passes back a memento to the originator to restore to a previous state.
It isn't permitted to modify a Memento object. 90
Memento pattern Behavioral Patterns
Memento

SAVING : To save the Originator's current internal state, the


Caretaker calls (createMemento()) on the Originator.
• The Originator creates a new Memento object, saves its current
internal state (setState()), and returns the Memento object to the
Caretaker.
• The Caretaker holds the returned Memento object(s).

RESTORING : To restore the Originator to a previous state, the


Caretaker calls restore(memento) on the Originator by providing
the Memento object to be restored.

• The Originator gets the state to be restored from the provided


Memento object (getState()).

CS3219 SEM1 AY2022/23 Ref: GoF


FYI: more links and information Behavioral Patterns
Memento

[Link]
- Example implementation of Memento pattern to solve the undo problem

- Memento Pattern within the Spring Framework in Spring Web flow ([Link]

- Memento pattern as a solution for thread safety problem in service classes.

CS3219 SEM1 AY2022/23 92


Behavioral Patterns
State

State pattern
“Allow an object to alter its behavior when its internal
state changes. The object will appear to change its class.” -- [GoF]

Source: [Link] 93
Behavioral Patterns
Example continued.. State

The Document object stores a reference


to one of the state objects that represents
its current state, and delegates all the
state-related work to that object.

To transition the Document into another


state, replace the active state object with
another object(Draft, Moderation,
Published) that represents that new state.

This is possible only if all state


classes(Draft, Moderation, Published)
follow the same interface and the
Document itself works with these objects
Source: [Link]
through that interface. 94
State pattern Behavioral Patterns
State

Intent : allow an object to alter its behavior when internal state


changes. “Object will appear to change class.”
• Domain objects often have a concept of state.
• Behavior of domain object (how it responds to client requests) depends on its
state, and client requests may change the state forcing the object to behave
differently after being invoked.
A typical approach to implement state-specific behavior is
directly within a class (Context) that depends on its
internal state.

Conditional statements (switch(state)) are required that


depend on this state.

Each conditional branch implements the corresponding


state-specific behavior. 95
State pattern Behavioral Patterns
State

Problem with the typical approach in handling state-specific behavior :

• Classes that include state-specific behavior are harder to


implement, change, test, and reuse.
"[…] we'd have look-alike conditional or case statements scattered
throughout Context's implementation. Adding a new state could require
changing several operations, which complicates maintenance." [GoF, p307]

• This is to be avoided.
We want
– that new states can be added and
– the behavior of existing states can be changed independently.

CS3219 SEM1 AY2022/23 96


State pattern Behavioral Patterns
State

Solution

– encapsulate state of such an object into separate classes


and
– at runtime delegate to the object representing the
current state – through what we know as polymorphism.
97
Participants of State pattern Behavioral Patterns
State

Context : Context stores a reference to one of the concrete state objects


and delegates to it all state-specific work. The context communicates with
the state object via the state interface. The context exposes a setter for
passing it a new state object.

State : an interface that encapsulates the behavior associated with a


particular state of the Context.
The State interface declares the state-specific methods. These methods
should make sense for all concrete states because you don’t want some of
your states to have useless methods that will never be called.

ConcreteState: Concrete class that implements a behavior associated with


a state of the Context. Concrete States provide their own
implementations for the state-specific methods. To avoid duplication of
similar code across multiple states, you may provide intermediate abstract
classes that encapsulate some common behavior.

State objects may store a backreference to the context object. Through


this reference, the state can fetch any required info from the context
object, as well as initiate state transitions.
Both context and concrete states can set the next state of the context and
perform the actual state transition by replacing the state object linked to
the context.
State pattern Behavioral Patterns
State
•The key idea in this pattern is to encapsulate an object's state-specific behavior in a
separate State object.
"This lets you treat the object's state as an object in its own right that can vary independently
from other objects." [GoF, p306]

•Define separate State objects:


• For all possible states, define a common interface for performing state-specific
behavior (State | operation(…)).
• Define classes (State1,State2,…) that implement the State interface for each
state.
“Because all state-specific code lives in a State subclass, new states and transitions can be
added easily by defining new subclasses." [GoF, p307]

•A class (Context) delegates the responsibility for performing state-specific behavior


to its current State object ([Link](…)).
99
FYI: more links and information Behavioral Patterns
State

[Link]
Example: candy machine

[Link]
The State pattern lets the same controls of the media player behave
differently, depending on the current playback state.

CS3219 SEM1 AY2022/23 100


Behavioral Patterns
Strategy

Strategy pattern
”lets you define a family of algorithms, put each of them into a separate class,
and make their objects interchangeable. “

Strategy Pattern State pattern


Source
[Link]

101
Behavioral Patterns
Example Strategy

A navigation app for casual travelers

automatic route planning

ver1- routes over roads


ver2 - walking routes
ver3 - public transport
….
….

Strategy Pattern

[Link]

102
Strategy pattern Behavioral Patterns
Strategy

Intent : represent a behavior that parameterizes an algorithm for


behavior or performance.
Very often applications use multiple algorithms to implement
some business requirements.

Example : Calculating prices in an order processing system


The price could be calculated in different ways e.g. depending on
type of customer, volume of sale, product quantity, etc.
It should be possible to select the right pricing algorithm (pricing
'strategy') .

Typical approach : implement an algorithm(s) directly within the


class (Context).
Use Conditional statements (switch(…)) to switch between
different algorithms.
103
Strategy pattern Behavioral Patterns
Strategy

Concerns : Typical approach (see previous slide) couples the class to particular algorithms and makes it difficult to
change an algorithm later independently from (without having to change) the class.
– Each time you add a new algorithm, the class would increase in size. At some point, it becomes too hard to maintain.
– Any change to one of the algorithms, whether it was a simple bug fix or a slight adjustment to a value/variable, affects the
whole class, increasing the chance of creating an error in already-working code.

à a clear violation of the Open Closed principle


à The violation occurred because we did not follow another fundamental practice “encapsulate what varies”.

"Hard-wiring all such algorithms into the classes that require them isn't desirable for several reasons:" [GoF, p315]

"Algorithms are often extended, optimized, and replaced during development and reuse." [GoF, p24]

Solution: The Strategy pattern suggests that you take a class that does something
specific in a lot of different ways and extract all of these algorithms into separate
classes called strategies.

CS3219 SEM1 AY2022/23 104


Behavioral Patterns
Strategy pattern Strategy

• Define a family of algorithms, encapsulate each one, and


make them interchangeable.

CS3219 SEM1 AY2022/23 105


Behavioral Patterns
Participants of the Strategy pattern Strategy

Context : Provides the interface to the client..


The Context maintains a reference to one of the concrete
strategies and communicates with this object only via the
Strategy interface.

Strategy : an interface common to all supported algorithm-


specific strategies. The Strategy interface is common to all
concrete strategies. It declares a method the context uses to
execute a strategy.
ConcreteStrategy : Concrete Strategies implement different
variations of an algorithm the context uses. Implements the
algorithm using the Strategy interface.
In the diagram on previous slide Strategy1 and Strategy2 are
ConcreteStrategy .

The Client creates a specific strategy object and passes it to the context.
The Context exposes a setter which lets clients replace the Strategy
associated with the Context at runtime.
The Context calls the execution method on the linked Strategy object each
time it needs to run the algorithm. The Context doesn’t know how the
algorithm is executed.
106
Strategy pattern Behavioral Patterns
Strategy

• The key idea is to implement algorithms in a separate inheritance


hierarchy so that they can vary independently.
• Define separate Strategy objects:
– For all supported algorithms, define a common interface for
performing an algorithm (Strategy | algorithm(…)).
– Define classes (Strategy1,Strategy2,…) that implement
the Strategy interface (encapsulate an algorithm).
• New algorithms can be added and existing ones can be changed
independently by defining new (sub)classes.
• A class (Context) delegates the responsibility for performing an
algorithm to a Strategy object ([Link](…)).
CS3219 SEM1 AY2022/23 107
Strategy pattern Behavioral Patterns
Strategy

Note:
• Strategy and State patterns appear similar.
• The structure of both the patterns are similar.
• It’s the intent that differs – that is, they solve different problems.
• The State pattern aims to facilitate state transition while the aim of the
Strategy pattern is to change the behavior of a class by changing internal
algorithm.

Strategy Pattern State pattern 108


FYI: more links and information Behavioral Patterns
Strategy

Two main implementation variants of Strategy


1: Push Data 2: Pull Data
•Context passes the data to the •Context passes nothing but itself to
strategy: the strategy, letting strategy call
[Link](data1,data2,…) back to get (pull) the required data
from context:
•The Strategy interface may get [Link](this)
complex because it must pass in the •The Context interface may have to
needed data for all supported be extended to let strategies do their
algorithms (whether they are simple work and access the needed data.
or complex).

[Link]
Example
Suppose you are building an In-Memory-Cache. ………… Some of the popular algorithms are:
•Least Recently Used (LRU): remove an entry that has been used least recently.
•First In, First Out (FIFO): remove an entry that was created first.
•Least Frequently Used (LFU): remove an entry that was least frequently used.

CS3219 SEM1 AY2022/23 109


Other Patterns
DTO

Data Transfer Object


Context
You are designing a distributed application, and to satisfy a single client request, you find yourself making
multiple calls to a remote interface, which increases the response time beyond acceptable levels.

Problem
How do you preserve the simple semantics of a procedure call interface without being subject to the latency
issues inherent in remote communication?

Solution DTO: “ to batch up what would be multiple remote calls into a single call”

Ref: Page 41
Martin Fowler, Patterns of EAA

[Link]

110
Data Transfer Object (DTO) Other Patterns
DTO

Intent: batch up multiple remote calls by encapsulating data that


needs to travel from one application/subsystem to another.
Benefit: to reduce roundtrips to the server by batching up multiple parameters in a single call.
This reduces the network overhead in such remote operations.

DTO: An object that encapsulates data, and is sent from one


node to another.
They are flat data structures that contain no business
logic. They only contain storage, accessors and eventually
methods related to serialization or parsing.

Source: [Link]
111
Data Transfer Object (DTO) Other Patterns
DTO
An object that carries data between processes in order to reduce the number of method
calls.

CS3219 SEM1 AY2022/23 Source: [Link] 112


Data Transfer Object (DTO) Other Patterns
DTO

Bundle all data items that might be needed into a single DTO
used for querying or updating attributes together

Ref page 418 Chapter 17 - POSA

CS3219 SEM1 AY2022/23 113


Data Transfer Object (DTO) Other Patterns
DTO

The DTO pattern is very useful whenever you are required to group values in
an ad-hoc structure just for the pure purpose of passing data around.

Use the Data Transfer Object pattern when:


•The client is asking for multiple information. And the information is related.
•You want reduced number of remote calls.
•When you want to boost the performance to get resources.

CS3219 SEM1 AY2022/23 114


Summary Summary

• Gang of Four patterns are extremely valuable


– They gave us a vocabulary
– And a way of thinking about software
– Coverage is incomplete / Definitions can be vague
• Look for patterns as you read and write software – GoF, non-GoF, and
undiscovered
• Don't use design patterns just for the sake of using them
– Only use them when they apply to a particular situation
– Specially, When some aspect of the system is most likely subject to change.
– Such situations most often recognized at design time or at refactoring
• Design patterns introduce more classes and objects. If elimination of a
pattern simplifies code, then do so.
• It is acceptable to modify a pattern to fit a particular problem. Such changes
should be documented to avoid confusion and make code more readable.

CS3219 SEM1 AY2022/23 115


Selected GoF Patterns for this lecture Summary

non-GoF /
Creational Structural Behavioral
others

Builder Adapter Mediator Data Transfer Object

Prototype Façade Memento

Bridge
(Ref slides under Observer
section on GoF on
creating good design)

State

Strategy

CS3219 SEM1 AY2022/23 116


Design patterns covered in L10&L11
Summary
Builder

Mediator

Prototype

Memento

Adapter

State

Bridge
Strategy

Façade

DTO

Observer
117

You might also like