SWEN20003 Object Oriented Software Development
SWEN20003
Object Oriented Software Development
Design Patterns
Semester 1, 2020
Design Patterns SWEN20003 Semester 1, 2020 1 / 57
The Road So Far
Java Foundations
Object Oriented Principles
I Encapsulation
I Information Hiding (Privacy)
I Inheritance and Polymorphsm
I Abstract Classes
I Interfaces
Modelling classes and relationships
Advanced Java
I Generics
I Exceptions
Design Patterns SWEN20003 Semester 1, 2020 2 / 57
Lecture Objectives
After this lecture you will be able to:
Describe what design patterns are, and why they
are useful
Analyse and understand design pattern
specifications
Make use of (some) design patterns
Design Patterns SWEN20003 Semester 1, 2020 3 / 57
Software Design
Are you already a good software designer?
If not, how do you become a good software designer?
Follow three simple steps…
Design Patterns SWEN20003 Semester 1, 2020 4 / 57
Software Design
Are you already a good software designer?
If not, how do you become a good software designer?
Follow three simple steps…
Design Patterns SWEN20003 Semester 1, 2020 4 / 57
Software Design
Are you already a good software designer?
If not, how do you become a good software designer?
Follow three simple steps…
Design Patterns SWEN20003 Semester 1, 2020 4 / 57
How to become a good software designer
Step 1: Learn the fundamentals of programming
Programming Languages
Algorithms and Data Structures
Step 2: Learn design paradigms and principles
Structured Design
Object Oriented Design
Step 3: Study and mimic the designs of experienced
designers
Good designers reuse solutions – they do not design
everything from scratch
Design Patterns systematically document
re-occurring design solutions so that they can be
reused
Design Patterns SWEN20003 Semester 1, 2020 5 / 57
How to become a good software designer
Step 1: Learn the fundamentals of programming
Programming Languages
Algorithms and Data Structures
Step 2: Learn design paradigms and principles
Structured Design
Object Oriented Design
Step 3: Study and mimic the designs of experienced
designers
Good designers reuse solutions – they do not design
everything from scratch
Design Patterns systematically document
re-occurring design solutions so that they can be
reused
Design Patterns SWEN20003 Semester 1, 2020 5 / 57
How to become a good software designer
Step 1: Learn the fundamentals of programming
Programming Languages
Algorithms and Data Structures
Step 2: Learn design paradigms and principles
Structured Design
Object Oriented Design
Step 3: Study and mimic the designs of experienced
designers
Good designers reuse solutions – they do not design
everything from scratch
Design Patterns systematically document
re-occurring design solutions so that they can be
reused
Design Patterns SWEN20003 Semester 1, 2020 5 / 57
Design Patterns
A Software Design Pattern is a description of a solution
to a recurring problem in software design.
The recurring nature of the problems makes the solution
useful to software developers.
Publishing it in the form of a Pattern enables the
solution to be used without reinventing the wheel.
Pioneering work on design patterns was done by Eric
Gamma and the team who authored the classic book on
design patterns (‘Gang of Four’):
Design Patterns SWEN20003 Semester 1, 2020 6 / 57
Analysing and Publishing a Pattern
Intent The goal of the pattern, why it exists
Motivation A scenario that highlights a need for the pattern
Applicability General situations where you can use the pattern
Structure Graphical representations of the pattern, likely a
UML class diagram
Participants List of classes/objects and their roles in the pattern
Collaboration How the objects in the pattern interact
Consequences A description of the results, side effects, and
tradeoffs when using the pattern
Implementation Example of “solving a problem” with the pattern
Known Uses Specific, real-world examples of using the pattern
Design Patterns SWEN20003 Semester 1, 2020 7 / 57
Analysing and Publishing a Pattern
Intent The goal of the pattern, why it exists
Motivation A scenario that highlights a need for the pattern
Applicability General situations where you can use the pattern
Structure Graphical representations of the pattern, likely a
UML class diagram
Participants List of classes/objects and their roles in the pattern
Collaboration How the objects in the pattern interact
Consequences A description of the results, side effects, and
tradeoffs when using the pattern
Implementation Example of “solving a problem” with the pattern
Known Uses Specific, real-world examples of using the pattern
Design Patterns SWEN20003 Semester 1, 2020 7 / 57
Analysing and Publishing a Pattern
Intent The goal of the pattern, why it exists
Motivation A scenario that highlights a need for the pattern
Applicability General situations where you can use the pattern
Structure Graphical representations of the pattern, likely a
UML class diagram
Participants List of classes/objects and their roles in the pattern
Collaboration How the objects in the pattern interact
Consequences A description of the results, side effects, and
tradeoffs when using the pattern
Implementation Example of “solving a problem” with the pattern
Known Uses Specific, real-world examples of using the pattern
Design Patterns SWEN20003 Semester 1, 2020 7 / 57
Analysing and Publishing a Pattern
Intent The goal of the pattern, why it exists
Motivation A scenario that highlights a need for the pattern
Applicability General situations where you can use the pattern
Structure Graphical representations of the pattern, likely a
UML class diagram
Participants List of classes/objects and their roles in the pattern
Collaboration How the objects in the pattern interact
Consequences A description of the results, side effects, and
tradeoffs when using the pattern
Implementation Example of “solving a problem” with the pattern
Known Uses Specific, real-world examples of using the pattern
Design Patterns SWEN20003 Semester 1, 2020 7 / 57
Analysing and Publishing a Pattern
Intent The goal of the pattern, why it exists
Motivation A scenario that highlights a need for the pattern
Applicability General situations where you can use the pattern
Structure Graphical representations of the pattern, likely a
UML class diagram
Participants List of classes/objects and their roles in the pattern
Collaboration How the objects in the pattern interact
Consequences A description of the results, side effects, and
tradeoffs when using the pattern
Implementation Example of “solving a problem” with the pattern
Known Uses Specific, real-world examples of using the pattern
Design Patterns SWEN20003 Semester 1, 2020 7 / 57
Analysing and Publishing a Pattern
Intent The goal of the pattern, why it exists
Motivation A scenario that highlights a need for the pattern
Applicability General situations where you can use the pattern
Structure Graphical representations of the pattern, likely a
UML class diagram
Participants List of classes/objects and their roles in the pattern
Collaboration How the objects in the pattern interact
Consequences A description of the results, side effects, and
tradeoffs when using the pattern
Implementation Example of “solving a problem” with the pattern
Known Uses Specific, real-world examples of using the pattern
Design Patterns SWEN20003 Semester 1, 2020 7 / 57
Analysing and Publishing a Pattern
Intent The goal of the pattern, why it exists
Motivation A scenario that highlights a need for the pattern
Applicability General situations where you can use the pattern
Structure Graphical representations of the pattern, likely a
UML class diagram
Participants List of classes/objects and their roles in the pattern
Collaboration How the objects in the pattern interact
Consequences A description of the results, side effects, and
tradeoffs when using the pattern
Implementation Example of “solving a problem” with the pattern
Known Uses Specific, real-world examples of using the pattern
Design Patterns SWEN20003 Semester 1, 2020 7 / 57
Analysing and Publishing a Pattern
Intent The goal of the pattern, why it exists
Motivation A scenario that highlights a need for the pattern
Applicability General situations where you can use the pattern
Structure Graphical representations of the pattern, likely a
UML class diagram
Participants List of classes/objects and their roles in the pattern
Collaboration How the objects in the pattern interact
Consequences A description of the results, side effects, and
tradeoffs when using the pattern
Implementation Example of “solving a problem” with the pattern
Known Uses Specific, real-world examples of using the pattern
Design Patterns SWEN20003 Semester 1, 2020 7 / 57
Analysing and Publishing a Pattern
Intent The goal of the pattern, why it exists
Motivation A scenario that highlights a need for the pattern
Applicability General situations where you can use the pattern
Structure Graphical representations of the pattern, likely a
UML class diagram
Participants List of classes/objects and their roles in the pattern
Collaboration How the objects in the pattern interact
Consequences A description of the results, side effects, and
tradeoffs when using the pattern
Implementation Example of “solving a problem” with the pattern
Known Uses Specific, real-world examples of using the pattern
Design Patterns SWEN20003 Semester 1, 2020 7 / 57
Analysing and Publishing a Pattern
Intent The goal of the pattern, why it exists
Motivation A scenario that highlights a need for the pattern
Applicability General situations where you can use the pattern
Structure Graphical representations of the pattern, likely a
UML class diagram
Participants List of classes/objects and their roles in the pattern
Collaboration How the objects in the pattern interact
Consequences A description of the results, side effects, and
tradeoffs when using the pattern
Implementation Example of “solving a problem” with the pattern
Known Uses Specific, real-world examples of using the pattern
Design Patterns SWEN20003 Semester 1, 2020 7 / 57
Design Patterns
Thousands of design patterns exist today.
Let us take a look as some common design patterns…
Design Patterns SWEN20003 Semester 1, 2020 8 / 57
Singleton Pattern
Ensure that a class has only one instance and provide a
global point of access to it.
Design Patterns SWEN20003 Semester 1, 2020 9 / 57
Singleton Pattern – Implementation
class Singleton {
private static Singleton _instance = null;
private Singleton() {
//fill in the blank
}
public static Singleton getInstance() {
if ( _instance == null )
_instance = new Singleton();
return _instance;
}
public void otherOperations() { }
}
Design Patterns SWEN20003 Semester 1, 2020 10 / 57
Singleton Pattern – Collaboration
class TestSingleton {
public void method1(){
X = Singleton.getInstance();
}
public void method2(){
Y = Singleton.getInstance();
}
}
Design Patterns SWEN20003 Semester 1, 2020 11 / 57
Singleton Pattern – Java Runtime Example
See full code at: link to java runtime code
public class Runtime {
private static Runtime currentRuntime = new Runtime();
private Runtime() {…}
public static Runtime getRuntime() {
return currentRuntime;
}
}
System.out.println(Runtime.getRuntime().availableProcessors());
System.out.println(Runtime.getRuntime().totalMemory());
Design Patterns SWEN20003 Semester 1, 2020 12 / 57
http://developer.classpath.org/doc/java/lang/Runtime-source.html
Singleton Pattern Analysis
Intent Ensure that a class has only one instance and
provide a global point of access to it.
Motivation There are cases where only one instance of a class
must be enforced with easy access to the object.
Applicability Use when a single instance of a class is required.
Structure See previous slides
Participants Singleton class.
Collaboration See previous slides.
Consequences Use it with caution because inappropriate use could
result in a bad design.
Implementation See previous slides.
Known Uses e.g. CacheManager class, PrinterSpooler class.
Design Patterns SWEN20003 Semester 1, 2020 13 / 57
Singleton Pattern Analysis
Intent Ensure that a class has only one instance and
provide a global point of access to it.
Motivation There are cases where only one instance of a class
must be enforced with easy access to the object.
Applicability Use when a single instance of a class is required.
Structure See previous slides
Participants Singleton class.
Collaboration See previous slides.
Consequences Use it with caution because inappropriate use could
result in a bad design.
Implementation See previous slides.
Known Uses e.g. CacheManager class, PrinterSpooler class.
Design Patterns SWEN20003 Semester 1, 2020 13 / 57
Singleton Pattern Analysis
Intent Ensure that a class has only one instance and
provide a global point of access to it.
Motivation There are cases where only one instance of a class
must be enforced with easy access to the object.
Applicability Use when a single instance of a class is required.
Structure See previous slides
Participants Singleton class.
Collaboration See previous slides.
Consequences Use it with caution because inappropriate use could
result in a bad design.
Implementation See previous slides.
Known Uses e.g. CacheManager class, PrinterSpooler class.
Design Patterns SWEN20003 Semester 1, 2020 13 / 57
Singleton Pattern Analysis
Intent Ensure that a class has only one instance and
provide a global point of access to it.
Motivation There are cases where only one instance of a class
must be enforced with easy access to the object.
Applicability Use when a single instance of a class is required.
Structure See previous slides
Participants Singleton class.
Collaboration See previous slides.
Consequences Use it with caution because inappropriate use could
result in a bad design.
Implementation See previous slides.
Known Uses e.g. CacheManager class, PrinterSpooler class.
Design Patterns SWEN20003 Semester 1, 2020 13 / 57
Singleton Pattern Analysis
Intent Ensure that a class has only one instance and
provide a global point of access to it.
Motivation There are cases where only one instance of a class
must be enforced with easy access to the object.
Applicability Use when a single instance of a class is required.
Structure See previous slides
Participants Singleton class.
Collaboration See previous slides.
Consequences Use it with caution because inappropriate use could
result in a bad design.
Implementation See previous slides.
Known Uses e.g. CacheManager class, PrinterSpooler class.
Design Patterns SWEN20003 Semester 1, 2020 13 / 57
Singleton Pattern Analysis
Intent Ensure that a class has only one instance and
provide a global point of access to it.
Motivation There are cases where only one instance of a class
must be enforced with easy access to the object.
Applicability Use when a single instance of a class is required.
Structure See previous slides
Participants Singleton class.
Collaboration See previous slides.
Consequences Use it with caution because inappropriate use could
result in a bad design.
Implementation See previous slides.
Known Uses e.g. CacheManager class, PrinterSpooler class.
Design Patterns SWEN20003 Semester 1, 2020 13 / 57
Singleton Pattern Analysis
Intent Ensure that a class has only one instance and
provide a global point of access to it.
Motivation There are cases where only one instance of a class
must be enforced with easy access to the object.
Applicability Use when a single instance of a class is required.
Structure See previous slides
Participants Singleton class.
Collaboration See previous slides.
Consequences Use it with caution because inappropriate use could
result in a bad design.
Implementation See previous slides.
Known Uses e.g. CacheManager class, PrinterSpooler class.
Design Patterns SWEN20003 Semester 1, 2020 13 / 57
Singleton Pattern Analysis
Intent Ensure that a class has only one instance and
provide a global point of access to it.
Motivation There are cases where only one instance of a class
must be enforced with easy access to the object.
Applicability Use when a single instance of a class is required.
Structure See previous slides
Participants Singleton class.
Collaboration See previous slides.
Consequences Use it with caution because inappropriate use could
result in a bad design.
Implementation See previous slides.
Known Uses e.g. CacheManager class, PrinterSpooler class.
Design Patterns SWEN20003 Semester 1, 2020 13 / 57
Singleton Pattern Analysis
Intent Ensure that a class has only one instance and
provide a global point of access to it.
Motivation There are cases where only one instance of a class
must be enforced with easy access to the object.
Applicability Use when a single instance of a class is required.
Structure See previous slides
Participants Singleton class.
Collaboration See previous slides.
Consequences Use it with caution because inappropriate use could
result in a bad design.
Implementation See previous slides.
Known Uses e.g. CacheManager class, PrinterSpooler class.
Design Patterns SWEN20003 Semester 1, 2020 13 / 57
Template Method and Strategy Patterns
Building generic components that can be extended,
adapted and re-used is key to good design.
The two main techniques that are used for developing
generic components are refactoring and generalizing.
identifying recurring code and replacing with generic
code
Inheritance and delegation are the two main OO design
techniques that are used for building generic components.
Design Patterns SWEN20003 Semester 1, 2020 14 / 57
Template Method and Strategy Patterns
Building generic components that can be extended,
adapted and re-used is key to good design.
The two main techniques that are used for developing
generic components are refactoring and generalizing.
identifying recurring code and replacing with generic
code
Inheritance and delegation are the two main OO design
techniques that are used for building generic components.
Design Patterns SWEN20003 Semester 1, 2020 14 / 57
Template Method and Strategy Patterns
Building generic components that can be extended,
adapted and re-used is key to good design.
The two main techniques that are used for developing
generic components are refactoring and generalizing.
identifying recurring code and replacing with generic
code
Inheritance and delegation are the two main OO design
techniques that are used for building generic components.
Design Patterns SWEN20003 Semester 1, 2020 14 / 57
Template Method and Strategy Patterns
Template Method and Strategy are two design patterns
that solve the problem of separating a generic algorithm
from a detailed design.
Template Method pattern uses Inheritance.
Strategy pattern uses Delegation.
Design Patterns SWEN20003 Semester 1, 2020 15 / 57
Template Method Pattern Motivation
public class BubbleSorter {
static int operations = 0;
public static int sort(int[] array){
operations = 0;
if (array.length <= 1) return operations; for (int i = array.length - 2; i >=0; i –){
for (int j = 0; j <= i; j++){ compareAndSwap(array, j); } } return operations; } contd... Design Patterns SWEN20003 Semester 1, 2020 16 / 57 Template Method Pattern Motivation public static void compareAndSwap(int[] array, int index){ if (array[index] > array[index+1])
swap(array,index);
operations++;
}
public static void swap(int[] array, int index){
int temp = array[index];
array[index] = array[index+1];
array[index+1] = temp;
}
}
Design Patterns SWEN20003 Semester 1, 2020 17 / 57
Template Method Pattern Example
public abstract class AbstractBubbleSorter {
private static int operations = 0;
protected int length = 0;
protected int doSort(){
operations = 0;
if (length <= 1) return operations; for (int i = length - 2; i >=0; i–){
for (int j = 0; j <= i; j++){ if (outOfOrder(j)) swap(j); operations++; } } return operations; } protected abstract void swap(int index); protected abstract boolean outOfOrder(int index); } Design Patterns SWEN20003 Semester 1, 2020 18 / 57 Template Method Pattern Example Design Patterns SWEN20003 Semester 1, 2020 19 / 57 Template Method Pattern Example public class IntBubbleSorter extends AbstractBubbleSorter { private int[] array = null; public int sort(int[] a){ array = a; length = array.length; return doSort(); } @Override protected boolean outOfOrder(int index) { return (array[index] > array[index+1]);
}
@Override
protected void swap(int index) {
int temp = array[index];
array[index] = array[index+1];
array[index+1] = temp;
}
}
Design Patterns SWEN20003 Semester 1, 2020 20 / 57
Template Method Pattern Structure
Design Patterns SWEN20003 Semester 1, 2020 21 / 57
Template Method Pattern Analysis
Intent Define a family of algorithms, encapsulate each
one, and make them interchangeable.
Motivation Build generic components that are easy to
extend and reuse.
Applicability Allows the implementation of invariant parts of
an algorithm once and leave it to the subclass to
implement the behavior that can vary.
Structure See previous slides.
Participants See previous slides.
Collaboration See previous slides.
Consequences All algorithms must use the same interface.
Implementation See previous slides.
Known Uses See previous slides.
Design Patterns SWEN20003 Semester 1, 2020 22 / 57
Template Method Pattern Analysis
Intent Define a family of algorithms, encapsulate each
one, and make them interchangeable.
Motivation Build generic components that are easy to
extend and reuse.
Applicability Allows the implementation of invariant parts of
an algorithm once and leave it to the subclass to
implement the behavior that can vary.
Structure See previous slides.
Participants See previous slides.
Collaboration See previous slides.
Consequences All algorithms must use the same interface.
Implementation See previous slides.
Known Uses See previous slides.
Design Patterns SWEN20003 Semester 1, 2020 22 / 57
Template Method Pattern Analysis
Intent Define a family of algorithms, encapsulate each
one, and make them interchangeable.
Motivation Build generic components that are easy to
extend and reuse.
Applicability Allows the implementation of invariant parts of
an algorithm once and leave it to the subclass to
implement the behavior that can vary.
Structure See previous slides.
Participants See previous slides.
Collaboration See previous slides.
Consequences All algorithms must use the same interface.
Implementation See previous slides.
Known Uses See previous slides.
Design Patterns SWEN20003 Semester 1, 2020 22 / 57
Template Method Pattern Analysis
Intent Define a family of algorithms, encapsulate each
one, and make them interchangeable.
Motivation Build generic components that are easy to
extend and reuse.
Applicability Allows the implementation of invariant parts of
an algorithm once and leave it to the subclass to
implement the behavior that can vary.
Structure See previous slides.
Participants See previous slides.
Collaboration See previous slides.
Consequences All algorithms must use the same interface.
Implementation See previous slides.
Known Uses See previous slides.
Design Patterns SWEN20003 Semester 1, 2020 22 / 57
Template Method Pattern Analysis
Intent Define a family of algorithms, encapsulate each
one, and make them interchangeable.
Motivation Build generic components that are easy to
extend and reuse.
Applicability Allows the implementation of invariant parts of
an algorithm once and leave it to the subclass to
implement the behavior that can vary.
Structure See previous slides.
Participants See previous slides.
Collaboration See previous slides.
Consequences All algorithms must use the same interface.
Implementation See previous slides.
Known Uses See previous slides.
Design Patterns SWEN20003 Semester 1, 2020 22 / 57
Template Method Pattern Analysis
Intent Define a family of algorithms, encapsulate each
one, and make them interchangeable.
Motivation Build generic components that are easy to
extend and reuse.
Applicability Allows the implementation of invariant parts of
an algorithm once and leave it to the subclass to
implement the behavior that can vary.
Structure See previous slides.
Participants See previous slides.
Collaboration See previous slides.
Consequences All algorithms must use the same interface.
Implementation See previous slides.
Known Uses See previous slides.
Design Patterns SWEN20003 Semester 1, 2020 22 / 57
Template Method Pattern Analysis
Intent Define a family of algorithms, encapsulate each
one, and make them interchangeable.
Motivation Build generic components that are easy to
extend and reuse.
Applicability Allows the implementation of invariant parts of
an algorithm once and leave it to the subclass to
implement the behavior that can vary.
Structure See previous slides.
Participants See previous slides.
Collaboration See previous slides.
Consequences All algorithms must use the same interface.
Implementation See previous slides.
Known Uses See previous slides.
Design Patterns SWEN20003 Semester 1, 2020 22 / 57
Template Method Pattern Analysis
Intent Define a family of algorithms, encapsulate each
one, and make them interchangeable.
Motivation Build generic components that are easy to
extend and reuse.
Applicability Allows the implementation of invariant parts of
an algorithm once and leave it to the subclass to
implement the behavior that can vary.
Structure See previous slides.
Participants See previous slides.
Collaboration See previous slides.
Consequences All algorithms must use the same interface.
Implementation See previous slides.
Known Uses See previous slides.
Design Patterns SWEN20003 Semester 1, 2020 22 / 57
Template Method Pattern Analysis
Intent Define a family of algorithms, encapsulate each
one, and make them interchangeable.
Motivation Build generic components that are easy to
extend and reuse.
Applicability Allows the implementation of invariant parts of
an algorithm once and leave it to the subclass to
implement the behavior that can vary.
Structure See previous slides.
Participants See previous slides.
Collaboration See previous slides.
Consequences All algorithms must use the same interface.
Implementation See previous slides.
Known Uses See previous slides.
Design Patterns SWEN20003 Semester 1, 2020 22 / 57
Strategy Pattern
Template method is an example of using inheritance as a
mechanism for re-use.
Generic algorithm is placed in the base class
Specific implementation is deferred to the sub class
The design tradeoff of using inheritance is the strong
dependency to the base class.
Although the methods outOfOrder and swap are
generic methods they cannot be re-used because
they inherit the AbstractBubbleSorter class
The Strategy pattern in an alternative.
Design Patterns SWEN20003 Semester 1, 2020 23 / 57
Strategy Pattern Example
public class BubbleSorterS {
static int operations = 0;
private int length = 0;
private SortHandle itsSortHandle = null;
public BubbleSorterS(SortHandle handle){
itsSortHandle = handle;
}
Contd..
Design Patterns SWEN20003 Semester 1, 2020 24 / 57
Strategy Pattern Example
public int sort(Object array){
itsSortHandle.setArray(array);
length = itsSortHandle.length();
operations = 0;
if (length <= 1) return operations; for(int nextToLast = length - 2; nextToLast >=0;nextToLast–){
for (int index=0; index <= nextToLast; index++){ if (itsSortHandle.outOfOrder(index)) itsSortHandle.swap(index); operations++; } } return operations; } } Design Patterns SWEN20003 Semester 1, 2020 25 / 57 Strategy Pattern Example public interface SortHandle { public void swap(int index); public boolean outOfOrder(int index); public int length(); public void setArray(Object array); } Design Patterns SWEN20003 Semester 1, 2020 26 / 57 Strategy Pattern Example public class IntSortHandle implements SortHandle { private int[] array = null; public int length() { return array.length; } public boolean outOfOrder(int index) { return (array[index] > array[index+1]);
}
public void setArray(Object array) {
this.array = (int [])array;
}
public void swap(int index) {
int temp = array[index];
array[index] = array[index + 1];
array[index + 1] = temp;
}
}
Design Patterns SWEN20003 Semester 1, 2020 27 / 57
Strategy Pattern Example
Design Patterns SWEN20003 Semester 1, 2020 28 / 57
Strategy Pattern Example
public class QuickBubbleSorterS {
static int operations = 0;
private int length = 0;
private SortHandle itsSortHandle = null;
public QuickBubbleSorterS(SortHandle handle){
itsSortHandle = handle;
}
public int sort(Object array){
itsSortHandle.setArray(array);
length = itsSortHandle.length();
operations = 0;
Contd…
Design Patterns SWEN20003 Semester 1, 2020 29 / 57
Strategy Pattern Analysis
if (length <= 1) return operations; boolean thisPassInOrder = false; for(int nextToLast = length - 2; nextToLast >=0 &&
!thisPassInOrder; nextToLast–){
thisPassInOrder = true;
for (int index=0; index <= nextToLast; index++){
if (itsSortHandle.outOfOrder(index)){
itsSortHandle.swap(index);
thisPassInOrder = false;
}
operations++;
}
}
return operations;
}
}
Design Patterns SWEN20003 Semester 1, 2020 30 / 57
Strategy Pattern Structure
Design Patterns SWEN20003 Semester 1, 2020 31 / 57
Factory Method Pattern
Creating objects in the class that requires (uses) the
objects is inflexible.
It commits the class to a particular object
Makes it impossible to change the instantiation
without having to change the class.
Factory Method pattern solves this problem by:
Defining a separate operation for creating an object.
Creating an object by calling a factory method.
Design Patterns SWEN20003 Semester 1, 2020 32 / 57
Factory Method Pattern
Keyword
Factory: A general technique for manufacturing
(creating) objects.
Keyword
Product: An abstract class that generalises the objects
being created/produced by the factory.
Keyword
Creator: An abstract class that generalises the objects
that will consume/produce products; generally have
some operation (e.g. the constructor) that will invoke
the factory method.
Design Patterns SWEN20003 Semester 1, 2020 33 / 57
Factory Method Pattern Example
Design Patterns SWEN20003 Semester 1, 2020 34 / 57
Factory Method Pattern Example
public abstract class Game {
private final List
public Game(int nPlayers) {
for (int i = 0; i < nPlayers; i++) {
players.add(createPlayer());
}
}
public abstract Player createPlayer();
}
Design Patterns SWEN20003 Semester 1, 2020 35 / 57
Factory Method Patter Example
public class RPGGame extends Game {
@Override
public Player createPlayer() {
return new RPGPlayer();
}
}
public class ShooterGame extends Game {
@Override
public Player createPlayer() {
return new ShooterPlayer();
}
}
RPGGame shadowQuest = new RPGGame();
ShooterGame callOfDuty = new ShooterGame();
Design Patterns SWEN20003 Semester 1, 2020 36 / 57
Factory Method Patter Example
Let’s say you want to implement a logging service:
class Logger {
public void log(String message, String loggerMedium) {}
}
where loggerMedium can be MEMORY, FILE, DB.
Design Patterns SWEN20003 Semester 1, 2020 37 / 57
Factory Method Patter Example
The naive way ...
class Logger {
public void log(String message, String loggerMedium) {
if (loggerMedium.equals("MEMORY")) {
logInMemory(message);
} else if (loggerMedium.equals("FILE")) {
logOnFile(message);
} else if (loggerMedium.equals("DB")) {
logToDB(message);
}
}
private void logInMemory(String message) {...}
private void logOnFile(String message) {...}
...
}
Design Patterns SWEN20003 Semester 1, 2020 38 / 57
Factory Method Patter Example
A better way ...
class Logger {
private InMemoryLog mLog; private FileLog fLog;
private DBLog dbLog;
public Logger() {
mLog = new InMemoryLog(); fLog = new FileLog();
dbLog = new DBLog();
}
public void log(String message, String loggerMedium) {
if (loggerMedium.equals("MEMORY")) {
mLog.logToMemory(message);
} else if (loggerMedium.equals("FILE")) {
fLog.logToFile(message);
} else if (loggerMedium.equals("DB")) {
dbLog.logToDB(message);
}
}
}
Design Patterns SWEN20003 Semester 1, 2020 39 / 57
Factory Method Patter Example
Any other better way? Yes! Use factory pattern.
class Logger {
public void log(String message, String loggerMedium) {
LoggingOperation instance =
LoggerFactory.getInstance(loggerMedium);
instance.log(message);
}
}
Our Logger is now much more elegant and decoupled
from creation of logging object services, e.g.,
InMemoryLog, etc. Object creation is now all centralised
to the factory.
Design Patterns SWEN20003 Semester 1, 2020 40 / 57
Factory Method Patter Example
Any other better way? Yes! Use factory pattern.
public interface LoggingOperation {
void log(String message);
}
class InMemoryLog implements LoggingOperation {
public void log(String message) {...}
}
class FileLog implements LoggingOperation {
public void log(String message) {...}
}
...
Design Patterns SWEN20003 Semester 1, 2020 41 / 57
Factory Method Patter Example
Any other better way? Yes! Use factory pattern.
class LoggerFactory {
private static final List
instances = new ArrayList<>();
static {
instances.addAll(Arrays.asList( new InMemoryLog(),
new FileLog(),
new DBLog()
));
}
public static LoggingOperation getInstance(
String loggerMedium) {
for(LoggingOperation op:instances) {
// If op matches your criteria return it.
}
return null;
}
}
Design Patterns SWEN20003 Semester 1, 2020 42 / 57
Factory Method Pattern
Design Patterns SWEN20003 Semester 1, 2020 43 / 57
Factory Method Pattern Structure
Summary: Benefits? Loose coupling between client
code and object creations. E.g., you need a car model,
then only need to tell the factory the model name. The
factory then creates a car with the model name for you.
You don’t need to know how that car is created, e.g.,
how a wheel, windows, body parts, etc are put together.
Design Patterns SWEN20003 Semester 1, 2020 44 / 57
Observer Pattern
There are situations where many objects (observers)
depend on the state of one object (subject).
A single object managing a one-to-many dependency
between objects is inflexible.
It commits (tightly couples) the subject to particular
dependent objects.
Such tightly coupled objects are hard to implement,
test and maintain.
Observer pattern decouples the subject and observers
using a publish-subscribe style communication pattern.
Design Patterns SWEN20003 Semester 1, 2020 45 / 57
Observer Pattern
Keyword
Subject: An “important” object, whose state (or change
in state) determines the actions of other classes.
Keyword
Observer: An object that monitors the subject in order
to respond to its state, and any changes made to it.
Design Patterns SWEN20003 Semester 1, 2020 46 / 57
Observer Pattern Example
Design Patterns SWEN20003 Semester 1, 2020 47 / 57
Observer Pattern Example
import java.util.ArrayList;
import java.util.List;
public class Subject {
private List
private int state;
public int getState() { return state;}
public void setState(int state) {
this.state = state;
notifyAllObservers();
}
public void attach(Observer observer){ observers.add(observer);}
public void notifyAllObservers(){
for (Observer observer : observers) {
observer.update();
}
}
}
Design Patterns SWEN20003 Semester 1, 2020 48 / 57
Observer Pattern Example
public abstract class Observer {
protected Subject subject;
public abstract void update();
}
public class BinaryObserver extends Observer{
public BinaryObserver(Subject subject){
this.subject = subject;
this.subject.attach(this);
}
@Override
public void update() {
System.out.println( “Binary String: ” +
Integer.toBinaryString( subject.getState() ) );
}
}
Design Patterns SWEN20003 Semester 1, 2020 49 / 57
Observer Pattern Example
public class OctalObserver extends Observer{
public OctalObserver(Subject subject){
this.subject = subject;
this.subject.attach(this);
}
@Override
public void update() {
System.out.println( “Octal String: ” +
Integer.toOctalString( subject.getState() ) );
}
}
public class HexaObserver extends Observer{
public HexaObserver(Subject subject){
this.subject = subject;
this.subject.attach(this);
}
@Override
public void update() {
System.out.println( “Hex String: ” +
Integer.toHexString( subject.getState() ).toUpperCase() );
}
}
Design Patterns SWEN20003 Semester 1, 2020 50 / 57
Observer Pattern Example
public class ObserverPatternDemo {
public static void main(String[] args) {
Subject subject = new Subject();
new HexaObserver(subject);
new OctalObserver(subject);
new BinaryObserver(subject);
System.out.println(“First state change: 15”);
subject.setState(15);
System.out.println(“Second state change: 10”);
subject.setState(10);
}
}
//First state change: 15
//Hex String: F Octal String: 17 Binary String: 1111
//Second state change: 10
//Hex String: A Octal String: 12 Binary String: 1010
Design Patterns SWEN20003 Semester 1, 2020 51 / 57
Observer Pattern Structure
Design Patterns SWEN20003 Semester 1, 2020 52 / 57
Observer Pattern
Why do we like this way better?
Automatically notifies observers of state changes
Decouples the subject and the observer
With some extra tools, powers a great deal of
event-driven programs
Clear responsibilities: subjects (ideally) know
nothing about the observers, except that they exist
Observers can be added and removed from subjects
at will, with zero effect (also known as the
publish-subscribe model)
Can be extended in various ways to improve
messaging, decoupling, and event-handling
Design Patterns SWEN20003 Semester 1, 2020 53 / 57
Observer Pattern
Why do we like this way better?
Automatically notifies observers of state changes
Decouples the subject and the observer
With some extra tools, powers a great deal of
event-driven programs
Clear responsibilities: subjects (ideally) know
nothing about the observers, except that they exist
Observers can be added and removed from subjects
at will, with zero effect (also known as the
publish-subscribe model)
Can be extended in various ways to improve
messaging, decoupling, and event-handling
Design Patterns SWEN20003 Semester 1, 2020 53 / 57
Design Patterns
Design Patterns: Elements of Reusable Object-Oriented
Software, a book written by the Gang of Four (or GoF)
describing 23 common software design patterns.
All good developers have seen most of the patterns, and
have an understanding of what they do, and what
common problems have already been solved.
Don’t reinvent the wheel… You’ll learn more about
patterns in SWEN30006.
Design Patterns SWEN20003 Semester 1, 2020 54 / 57
Design Patterns
Commonly solved classes of problems:
Creational Solutions related to object creation,
e.g. Singleton, Factory Method
Structural Solutions dealing with the structure of
classes and their relationships,
e.g. Adapter, Bridge
Behavioural Solutions dealing with the interaction
among classes,
e.g. Strategy, Template Method, Observer
Design Patterns SWEN20003 Semester 1, 2020 55 / 57
Review
1 Identify where the patterns covered in the lecture
can be applied to the project
2 Describe the advantages of using design patterns (in
general)
3 Describe the core components (the analysis) of the
patterns covered in the lecture
Design Patterns SWEN20003 Semester 1, 2020 56 / 57
Lecture Objectives
You should be able to:
Describe what design patterns are, and why they
are useful
Analyse and understand design pattern
specifications
Make use of (some) design patterns
Design Patterns SWEN20003 Semester 1, 2020 57 / 57