L10 11-ObjectInteractionDesignPatterns
L10 11-ObjectInteractionDesignPatterns
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
CANVASàWeblinks
//OTOT Z1 from last year – just some samples
Selected Patterns
Selected Patterns
and
SEM1 AY2022/23 Source: Chapter 5 Design Patterns Explained by Shalloway & Trott 6
From Architectural to Software Design patterns Patterns -
background
“the Gang of Four(GoF) book” features patterns solving various problems of o-o design.
7
Patterns -
The GoF Design Patterns background
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
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
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
Factory
Prototype Singleton
Abstract
Factory
Builder
Proxy Façade
Flyweight Bridge
Chain of
Responsibility
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’
“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…….”
23
GoF patterns -
overview
Example: Design a
24
Stack Version 1 (is-A)
25
GoF patterns -
overview
principle
Favor over
Inheritance 26
GoF patterns -
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.
[Link]();
[Link]();
[Link]();
[Link]();}
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
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)
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
• 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
Selected Patterns
non-GoF /
Creational Structural Behavioral
others
Data Transfer
Builder Adapter Mediator
Object
Bridge
Observer
(Ref slides in earlier
section -GoF on
creating good design)
State
Strategy
Builder
A creational pattern
The creational design patterns deal with object creation mechanisms.
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.
Basic house
Additional Representation
43
Creational Patterns
Example – House Builder Builder
- & 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
“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
[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,
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.
51
Prototype pattern 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
Prototype: a Java interface or abstract class that defines the contract for
classes that permits cloning of its objects.
Another related concept is that of Object cloning : Deep and Shallow copy
The adapter design pattern allows the interface of an existing class to be used from another interface.
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.
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
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.
Example: [Link]
[Link]
[Link]
69
Structural Patterns
Participants of the Façade pattern: Facade
Db
Image source: [Link]
Product Data +Store(productionData) Application
+GetProduct(sku)
+DeleteProductData(sku)
[Link]
[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]
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.
[Link]
CS3219 SEM1 AY2022/23 74
Behavioral Patterns
Participants of the Observer pattern 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
[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.
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
Ref: GoF
[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. …
Memento
”allow client to capture an object’s state, and restore”
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 .
[Link]
89
Participants of Memento pattern 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]
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
• This is to be avoided.
We want
– that new states can be added and
– the behavior of existing states can be changed independently.
Solution
[Link]
Example: candy machine
[Link]
The State pattern lets the same controls of the media player behave
differently, depending on the current playback state.
Strategy pattern
”lets you define a family of algorithms, put each of them into a separate class,
and make their objects interchangeable. “
101
Behavioral Patterns
Example Strategy
Strategy Pattern
[Link]
102
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.
"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.
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
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.
[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.
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
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.
Bundle all data items that might be needed into a single DTO
used for querying or updating attributes together
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.
non-GoF /
Creational Structural Behavioral
others
Bridge
(Ref slides under Observer
section on GoF on
creating good design)
State
Strategy
Mediator
Prototype
Memento
Adapter
State
Bridge
Strategy
Façade
DTO
Observer
117