Week 7 Design Patterns1a
Week 7 Design Patterns1a
1
LEARNING OBJECTIVES
2
INTRODUCTION TO PATTERNS
Solution to commonly occurring or recurring aspects of design
problems
Allows you to use previously outlined solutions that expert developers
have used
A pattern is the outline of a reusable solution to a general problem
encountered in a particular context
Object oriented design and not code in a programming language
Represented abstractly, explained with examples
A good pattern should
Be as general as possible
3
Contain a solution that has been proven to effectively solve the problem in
the indicated context.
INTRODUCTION TO PATTERNS
5
DESCRIBING A PATTERN
Specify the generic problem that is to be solved
Which design pattern to use to solve a software design
problem, especially as many design patterns exist?
Motivate the design pattern solution with the help of an
example
Provide the structure for the pattern
Discuss the collaboration between the classes
Discuss other issues related to the pattern such as trade offs
and implementation techniques 6
PATTERN BY GANG OF FOUR (GOF)
3 x different categories:
• creational patterns
• structural patterns
• behavioral patterns
7
GOF DESIGN PATTERNS
CLASSIFICATION
Creational
Concern the process of object creation
Structural
Deal with the composition of classes or objects
Behavioral
Characterize the ways in which classes or objects interact
and distribute responsibility
8
PATTERN DESCRIPTION TEMPLATE
PROVIDED BY GOF
9
CREATIONAL DESIGN PATTERN
10
EXAMPLES OF CREATIONAL PATTERN
Abstract Factory
Provide an interface for creating families of related or dependent objects without specifying their concrete
classes.
Builder
Separate the construction of a complex object from its representation so that the same construction
process can create different representations.
Factory Method
Define an interface for creating an object, but let subclasses decide which class to instantiate. Factory
Method lets a class defer instantiation to subclasses.
Prototype
Specify the kinds of objects to create using a prototypical instance, and create new objects by copying this
prototype.
11
Singleton
Ensure a class only has one instance, and provide a global point of access to it.
STRUCTURAL DESIGN PATTERN
12
GOF STRUCTURAL PATTERNS
Template Method
Lets certain steps in a super class be defined by sub class.
Strategy
encapsulate family of algorithm and make them interchangeable.
Iterator
Provide a way to access the elements of an aggregate object sequentially
without exposing its underlying representation.
Observer
when one object changes state, all its dependents are notified and updated
automatically.
State
15
Allow an object to alter its behavior when its internal state changes. The
object will appear to change its class
GOF 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.
Memento
Without violating encapsulation, capture and externalize an object's internal state so that the
object can be restored to this state later.
. Visitor
Represent an operation to be performed on the elements of an object structure. Visitor lets you
define a new operation without changing the classes of the elements on which it operates.
Chain of Responsibility
Avoid coupling the sender of a request to its receiver by giving more than one object a chance
16 to
handle the request. Chain the receiving objects and pass the request along the chain until an
object handles it.
GOF BEHAVIORAL PATTERNS
Command
Encapsulate a request as an object, thereby letting you
parameterize clients with different requests, queue or log
requests, and support undoable operations.
Interpreter
Given a language, define a representation for its grammar along
with an interpreter that uses the representation to interpret
sentences in the language.
17
18
SCOPE OF PATTERNS
19
GOF ESSENTIAL ELEMENTS OF
PATTERNS
Pattern Name
Having a concise, meaningful name for a pattern improves
communication among developers
Problem
What is the problem and context where we would use this pattern?
Solution
A description of the elements that make up the design pattern
Emphasizes their relationships, responsibilities and collaborations
Not a concrete design or implementation; rather an abstract
description
Consequences 20
22
SINGLETON DESIGN PATTERN
A singleton is a creational pattern, which describes a way to create an
object
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 23
EXAMPLE
Enforces one and only one object of a singleton class
24
SOLUTION
25
EXAMPLE
ExampleSingleton
-
instance:ExampleSingleton
-ExampleSingleton()
+getInstance():ExampleSingleto
n
+showmessage():void
27
SOME OTHER KEY FACTS
28
FACTORY METHODS PATTERN
29
FACTORY METHODS PATTERN
Factory Object
30
FACTORY METHODS PATTERN
31
FACTORY METHODS PATTERN
Smartphone ordersmartphone(String smartphoneType)
{
Smartphone smartphone = null; // create smartphone object
If (smartphoneType.equals(“samsung”))
{ Concrete instantiation is
smartphone = new samsungGalaxyS20(); indicated with the operator
Huawei P30 Pro
} “new”
else if (smartphoneType.equals(“iphone”))
{
smartphone = new iphone12();
}
// prepare smartphone
smartphone.embellish()
smartphone.polish()
smartphone.packaging()
return smartphone; 32
} Google Pixel 4A
FACTORY METHODS PATTERN
Smartphone ordersmartphone(String smartphoneType)
{
Smartphone smartphone = null; // create smartphone object
If (smartphoneType.equals(“samsung”))
{
smartphone = new samsungGalaxyS20(); Concrete instantiation is
}
else if (smartphoneType.equals(“iPhone”)) indicated with the operator
{ “new” Huawei phone
smartphone = new iPhone12();
else if (smartphoneType.equals(“Huawei”))
{
smartphone = new Huaweip30pro();
}
else if (smartphoneType.equals(“Google”))
{
smartphone = new GooglePixel4A();
}
// prepare smartphone
smartphone.embellish()
smartphone.polish()
Generic functions applied to all
smartphone.packaging() smartphone types Google Pixel 4A
return smartphone; 33
}
FACTORY METHODS PATTERN
34
FACTORY METHODS PATTERN
}
FACTORY METHODS PATTERN
public class SmartphoneStore {
private SmartphoneFactory factory;
Public SmartphoneStore(smartphoneFactory factory)
{ // require a smartphoneFactory object to
be passed to this constructor:
this.factory = factory;
}
Public Smartphone ordersmartphone(String smartphoneType)
{
Smartphone smartphone;
smartphone = factory.createsmartphone(smartphoneType); //use the create method in
//prepare the smartphone the factory
smartphone.embellish();
smartphone.polish();
smartphone.package();
return smartphone; 36
}
}
FACTORY METHODS PATTERN
37
FACTORY METHODS PATTERN
The factory method design intent is to define an interface for creating objects, but let the
sub-classes decide which class to instantiate
}
FACTORY METHODS PATTERN
smartphone smartphoneStore
ordersmartphone()
createsmartphone()
BasicSamsungPhone BasicSmartphoneStore
createsmartphone()
40
FACTORY METHODS PATTERN
41
https://www.youtube.com/watch?v=pt1IbV1aSZ4
SUMMARY
A factory is generally a method or object that allows you to create other objects
Act of object creation, usually with the new keyword in Java is called concrete
instantiation
A factory object may be a useful tool if many parts of the software want to create
the same objects
Factory method pattern is a little bit different. Instead of using another object to
create objects, we separate out object creation into another method, a Factory
method
By separating the actual object creation from other behavior using factories, the
code becomes cleaner to read and easier to maintain or change
42
PROTOTYPE DESIGN PATTERN
43
PROTOTYPE DESIGN PATTERN
A problem
In a graphical; editor, by clicking on an object one can obtain
the copy of an original object. Obtaining the copy of an
existing object is a common design problem in online
composition
We can provide a design solution to solve this problem, and
reuse this design whenever similar solution arises.
44
PROTOTYPE PATTERN
proto->clone()
CirclePrototype RectanglePrototype
clone() clone()
45
proto->clone()
ConcretePrototype I ConcretePrototype II
clone() clone()
46
48
STRUCTURAL DESIGN PATTERNS
49
ADAPTOR METHOD (STRUCTURAL)
50
SOLUTION
Insert () Push()
Fetch () Pop()
FIFO LIFO
Insert () Insert ()
Fetch () Fetch ()
51
Push()
ADAPTER
Request () specificReq()
Adapter
Request ()
52
specificRequest ()
ADAPTER
Request () specificReq()
Adaptee
Adapter
Request ()
53
Adaptee->specificRequest ()
FACADE PATTERN
Context:
Often, an application contains several complex packages.
A programmer working with such packages has to manipulate many different
classes
Problem:
How do you simplify the view that programmers have of a complex package?
Forces:
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 these classes. 54
FACADE
Solution:
55
STRUCTURAL DESIGN PATTERN
Reference:
https://freevideolectures.com/course/2318/software-engineering/15
Object-Oriented Software Engineering: Practical Software Development using UML
and Java by Timothy C. Lethbridge and Robert Laganière, 2004.
56
BEHAVIORAL DESIGN PATTERNS
57
STATE DESIGN PATTERN (BEHAVIORAL)
58
STATE PATTERN (EXAMPLE)
Vending machines have states based on the inventory, amount of currency
deposited, the ability to make change, the item selected, etc.
When currency is deposited and a selection is made, a vending machine
will either deliver a product and no change, deliver a product and change,
deliver no product due to insufficient currency on deposit, or deliver no
product due to inventory depletion.
59
STATE PATTERN (EXAMPLE)
60
STATE PATTERN
61
STATE PATTERN
62
STATE PATTERN
63
STATE PATTERN
64
STATE PATTERN
65
STATE PATTERN
66
STATE PATTERN
67
STATE PATTERN
68
STATE PATTERN
69
STATE PATTERN
70
STATE PATTERN
71
STATE PATTERN
72
STATE PATTERN
73
STATE PATTERN
74
STATE PATTERN (SUMMARY)
76
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
77
OBSERVER PATTERN
Solution:
78
OBSERVER PATTERN
Antipatterns:
Connect an observer directly to an observable so that they both have references to each
other.
Make the observers subclasses of the observable.
79
OBSERVER PATTEN
Reference:
Object-Oriented Software Engineering: Practical Software Development using UML
and Java by Timothy C. Lethbridge and Robert Laganière, 2004.
80
COMMAND DESIGN PATTERN
81
COMMAND PATTERN
82
COMMAND PATTERN
83
COMMAND PATTERN
84
COMMAND PATTERN
85
The classes participating in the pattern are:
Command
declares an interface for executing an operation;
ConcreteCommand
extends the Command interface, implementing the Execute method by invoking the
corresponding operations on Receiver. It defines a link between the Receiver and the
action.
Client - creates a ConcreteCommand object and sets its receiver;
Invoker - asks the command to carry out the request;
87
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
88
ABSTRACTION-OCCURRENCE
Solution:
89
ABSTRACTION-OCCURRENCE
Antipatterns:
90
ABSTRACTION-OCCURRENCE
Square variant
91
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).
Solution:
93
GENERAL HIERARCHY
Solution:
94
GENERAL HIERARCHY
Antipattern:
95
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?
96
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:
97
PLAYER-ROLE
Example 1:
98
PLAYER-ROLE
Example 2:
99
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.
100
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
101
SINGLETON
Solution:
102
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
103
OBSERVER
Solution:
104
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.
105
6.7 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
106
DELEGATION
Solution:
107
DELEGATION
Example:
108
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
return getRegularFlight().flightNumber();
109
6.8 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.
110
ADAPTER
Solution:
111
ADAPTER
Example:
112
6.9 THE FAÇADE PATTERN
Context:
Often, an application contains several complex packages.
A programmer working with such packages has to manipulate many different
classes
Problem:
How do you simplify the view that programmers have of a complex package?
Forces:
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
these classes.
113
FAÇADE
Solution:
114
6.10 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
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.
115
6.11 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
116
READ-ONLY INTERFACE
Solution:
117
READ-ONLY INTERFACE
Example:
118
READ-ONLY INTERFACE
Antipatterns:
Make the read-only class a subclass of the «Mutable» class
Override all methods that modify properties
such that they throw an exception
119
6.12 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
120
PROXY
Solution:
121
PROXY
Examples:
122
6.13 THE FACTORY PATTERN
Context:
A reusable framework needs to create objecs; however the class of the created objects depends
on the application.
Problem:
How do you enable a programmer to add new application-specific class into a system built on
such a framework?
Forces:
We want to have the framework create and work with application-specific classes that the
framework does not yet know about.
Solution:
The framework delegates the creation of application-specific classes to a specialized class, the
Factory.
The Factory is a generic interface defined in the framework.
The factory interface declares a method whose purpose is to create some subclass of a generic
class.
123
THE FACTORY PATTERN
Solution
124
THE FACTORY PATTERN
Example
125
6.14 DETAILED EXAMPLE: ENHANCING OCSF
WITH SOME DESIGN PATTERNS
126
THE OBSERVABLE LAYER OF OCSF
(CONTINUED)
127
USING THE OBSERVABLE LAYER
1. Create a class that implements the Observer interface.
2. Register it as an observer of the Observable:
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.
129
DIFFICULTIES AND RISKS WHEN CREATING
CLASS DIAGRAMS
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.
130