Reminders and Clarifications
• Each sprint must be documented in the GitLab wiki
– Sprint Milestones are not accurate historical documents, since unfinished stories may be moved to the next Sprint Milestone, or put back in the Product Backlog due to new priorities
– Wiki should document your sprint goals, progress, evidence of completed tasks (e.g. successful unit testing), and sprint retrospective
– wiki will help your TAs know what’s been done, and know where to look for relevant project work related to the sprint
• To help connect program changes to Sprint backlog items (i.e. stories), use the “refs”, “fixes” or “closes” GitLab commit message keywords when you commit your changes
CIS 3760
Software Engineering
1
g
g
l
t
li
i
n
“
#
#
“
“
c
c
i
it
n
k
“T
t
c
T
1
k
1,
T
T
l
c
h
s
o
o
st
hi
i
,f
h
hi
lo
o
i
s
m
m
m
t
o
o
i
s
f
s
s
c
se
e
s
m
i
sc
i
is
ix
s
#
s
x
i
t
tc
s
s
u
co
o
e
e
co
u
e
co
m
s
o
m
es
mm
s
#
mi
s#
om
#
m
1
15
m
m
5
m
m
it
#
i
i
)
)
m
e
#1
1
–
tr
2
2
t
t
”
”
o
en
-3
r
nt
3
:
:
e
ef
fs
or
r
s
Software Patterns
Part I: Intro and Architectural Patterns Intro to reuse and software patterns
Some system design definitions
Architectural patterns
Part II: Design patterns
CIS 3760
Software Engineering
2
CIS 3760: Software Engineering Software Patterns
Part II – Design Patterns
Instructor: Prof. Stacey Scott
School of Computer Science
University of Guelph https://www.uoguelph.ca/computing/people/stacey-scott stacey.scott@uoguelph.ca
©2017-21 Stacey D. Scott
Introduction to Design Patterns Video
• Lynda.com Course: What are design patterns?
– “The need for a design pattern” module:
– https://www.linkedin.com/learning/ c-plus-plus-design-patterns-creational/ the-need-for-a-design-pattern?u=56996833
– (a module from the course: C++ Design Patterns: Creational)
– “What are design patterns” module:
https://www.linkedin.com/learning/ c-plus-plus-design-patterns-creational/ what-are-design-patterns?u=56996833
CIS 3760
Software Engineering
4
Home Viewing: Difference between Architectural Patterns and Design Patterns
• Lynda.com Course: Patterns and frameworks
– Architectural vs. design patterns module:
– https://www.linkedin.com/learning/python-advanced-design- patterns/architectural-vs-design-patterns?u=56996833
– (a module from the course: Python: Advanced Design Patterns)
CIS 3760
Software Engineering
5
Required Readings from
“Dive into Design Patterns” by A. Shvets
• Shvets pp. 23-28 (Intro to design patterns) – basics concepts of design patterns
• Shvets pp. 29-47 (S/W design principles) – code reuse, extensibility, encapsulation, programming to an interface, composition (or delegation) vs. inheritance
– Optional reading: SOLID principles (pp. 48-67)
• Shvets pp. 68-70 (Catalogue of Design Patterns)
• Shvets pp. 71-102 (Factory Method & Abstract Factory patterns)
• Shvets pp. 146, 149-161 (Adapter pattern)
• Shvets pp. 146, 162-176 (Bridge pattern)
• Shvets pp. 248, 336-351 (Observer pattern)
CIS 3760
Software Engineering
6
Section Outline
• Key reuse & object-oriented design concepts
• Delegation (Composition) and inheritance in a sample design pattern
– Adapter pattern
• Types of design patterns & strategies to select & apply design patterns
• Sample patterns
– Observer pattern
– Bridge pattern
– Factory Method pattern
– Abstract Factory pattern
CIS 3760
Software Engineering
7
Reuse: Composition vs. Inheritance
• Main goal:
– Reuse knowledge from previous experience to current problem
– Reuse functionality already available
• Composition (also called Black Box Reuse)
– New functionality is obtained by composition (or aggregation)
– The new object with more functionality is composed of existing components
• Inheritance (also called White-box Reuse)
– New functionality is obtained by inheritance
• Three ways to get new functionality: Implementation inheritance
Specification inheritance
Delegation (aka Composition)
CIS 3760
Software Engineering
8
Slides adapted from Bruegge & Dutoit, Pearson
Examples: Composition vs
Taxonomy (i.e. a classification into ordered categories)
• Which model is which?
Mammal
Incident Report
Text box
Menu
Scrollbar
Tiger
Wolf
Whale
CIS 3760
Software Engineering
9
Slides adapted from Bruegge & Dutoit, Pearson
Composition vs. Inheritance Video and Concepts Discussion
• Composition over Inheritance by Mattias Petter Johansson • https://youtu.be/wfMtDGfHWpA
• Video Script: https://medium.com/humans-create- software/composition-over-inheritance-cb6f88070205
– With sample JavaScript
CIS 3760
Software Engineering
10
His original taxonomy
Mattias Petter
Johansson from Fun Fun Function YouTube Channel
Animal
poop()
Robot
drive()
Dog
bark()
CleaningRobot
MurderRobot
Cat
clean()
kill()
meow()
CIS 3760
Software Engineering
11
Now, wait!
The Client has asked for a MurderRobotDog that can drive, kill, bark, but not poop!
CIS 3760
Software Engineering
12
Design improvement through Composition
To solve this problem, Mattias recommends using Composition
CIS 3760
Software Engineering
13
System Designs in UML
Animal
poop()
Robot
drive()
CleaningRobot
MurderRobot
Dog
Cat
Objects/Classes
clean()
kill()
bark()
meow()
CIS 3760
Software Engineering
14
System Designs in UML
Cat
pooper
meower
barker
CleaningRobot
Dog
cleaner
MurderRobotDog
driver
killer
CIS 3760
Software Engineering
15
MurderRobot
Inheritance or Composition?
CIS 3760
Software Engineering
16
Consider the following two models
• Which model is easier to intuitively understand?
• If we discovered that
all animals also needed eat(), drink(), and pee() behaviours, which model
is easier to propagate these changes?
• Beyond conceptual
and structural system
design, the “composition only”
model restricts certain flexible
computational behaviour,
such as deferred object binding
that we will see later (e.g. Bridge Design
Pattern)
Animal
poop()
Robot
drive()
CleaningRobot
MurderRobot
Dog
Cat
clean()
kill()
bark()
meow()
pooper
Cat
meower
barker
CleaningRobot
Dog
cleaner
MurderRobotDog
driver
killer
CIS 3760
Software Engineering
17
MurderRobot
The following combined use of inheritance AND composition provides a compromise
Animal
poop()
Robot
drive()
Dog
bark()
CleaningRobot
clean()
MurderRobot
Cat
MurderRobotDog
kill()
Design Patterns rely heavily on combining inheritance and composition (also called delegation) to gain the respective SE benefits of both reuse approaches
meow()
kill()
bark()
CIS 3760
Software Engineering
18
Types of Inheritance: Implementation vs. Specification
• Implementation inheritance
– Goal: Extend an applications’ functionality by reusing functionality
in parent class
– Inherit from an existing class with some or all operations already implemented
• Specification inheritance
– Goal: increase reusability, enhance modifiability and extensibility
– Inherit from an abstract class with all operations specified, but not yet implemented
CIS 3760
Software Engineering
19
Slides adapted from Bruegge & Dutoit, Pearson
Composition/Delegation instead of Implementation Inheritance
• Implementation Inheritance: Extending a base/parent class by a new operation or overwriting an operation
• Delegation (Composition): Catching an operation and sending it to another object
Delegation is a way to implement a stack class while reusing the behaviours of a List
List
+Add() +Remove()
+Push() +Pop() +Top()
Remove() Add()
Stack
+Push() +Pop() +Top()
CIS 3760
Software Engineering
20
Slides adapted from Bruegge & Dutoit, Pearson
Stack
List
Comparison: Composition (Delegation) vs Implementation Inheritance
Pros
Cons
Composition
• Adaptability: Can reuse only parts of an existing object that are needed in the context, without exposing irrelevant behaviours
• Inefficiency: Objects are encapsulated
CIS 3760
Software Engineering
Inheritance
• Straightforward to use
• Supported by many programming
languages
• Easy to implement new
functionality
• Inheritance exposes a subclass to the (potentially irrelevant) details of its parent class
• Any change in the parent class implementation forces the subclass to change (which requires recompilation of both)
21
Slides adapted from Bruegge & Dutoit, Pearson
Where are we? Section Outline
Key reuse & object-oriented design concepts
Delegation (aka Composition) and inheritance in a
sample design pattern (Adapter)
• Types of design patterns & strategies to select & apply design patterns
• Sample patterns – Observer
– Factory Method
– Abstract Factory – Bridge
CIS 3760
Software Engineering
22
Review
• What is Black-box reuse? What is White-box Reuse?
• What is delegation? calls
delegates to
Client
Receiver
Delegate
CIS 3760
Software Engineering
23
Review: Implementation or Specification Inheritance
Diagram A Diagram B
CIS 3760
Software Engineering
24
Example Design Pattern: Adapter Pattern
Problem: You’re traveling in Europe and want to charge your laptop…
CIS 3760
Software Engineering
26 p 236, Head First Design Patterns, Freeman et al. text
Solution: A (Power) Adapter
CIS 3760
Software Engineering
27 Head First Design Patterns, Ch 7, Freeman et al. text
Example Design Pattern: Adapter Pattern
• Adapter Pattern: Connects incompatible components
– It converts the interface of one component into another interface expected by the other (calling) component
– Used to provide a new interface to existing legacy components (interface engineering, reengineering)
• Also known as a wrapper
CIS 3760
Software Engineering
28
Slides adapted from Bruegge & Dutoit, Pearson
Adapter Pattern
New System
<
ClientInterface
request()
Old System (“Legacy System”)
Delegation
Inheritance
LegacyClass
(Adaptee)
existingRequest()
Adapter
request()
The adapter pattern uses inheritance as well as delegation:
– Interface inheritance: Adapter inherits Request() from ClientInterface – Delegation: Binds LegacyClass to the Adapter.
CIS 3760
Software Engineering
29
Slides adapted from Bruegge & Dutoit, Pearson
Client
Adapter Pattern: AC-to-EU Power Adapter
YourLaptop
ACPlug
(interface class)
plugIn()
EUWallOutlet
plugInEU()
ACtoEUAdapter
plugIn()
CIS 3760
Software Engineering
30
Implementation in Java
ACPlug
public interface ACPlug {
public void acPlugIn(); ACtoEUAdapter
}
public class ACtoEUAdapter implements ACPlug { private EUWallOutlet euOutlet;
public ACtoEUAdapter (EUWallOutlet euOutlet) {
this.euOutlet = euOutlet;
}
void acPlugIn() {
acPlugIn()
Laptop
EUWallOutlet
euPlugIn()
} }
…in main:
…
// convert voltages (120v/60Hz->230v/50Hz) euOutlet.euPlugIn();
EUWallOutlet euOutlet = new EUWallOutlet(); ACPlug laptopPlug = new ACtoEuAdapter(euOutlet); laptopPlug.acPlugIn();
CIS 3760
Software Engineering
31 Head First Design Patterns, Ch 7, Freeman et al. text
acPlugIn()
Implementation in Java
public interface ACPlug {
public void acPlugIn();
}
ACtoEUAdapter
ACPlug
acPlugIn()
Laptop
EUWallOutlet
euPlugIn()
Delegate object
public class ACtoEUAdapter implements ACPlug {
private EUWallOutlet euOutlet;
public ACtoEUAdapter (EUWallOutlet euOutlet) {
this.euOutlet = euOutlet;
}
void acPlugIn() {
sets the delegation
// convert voltages (120v/60Hz->230v/50Hz)
euOutlet.euPlugIn();
passes the request to delegate object
} }
…in main:
EUWallOutlet euOutlet = new EUWallOutlet(); ACPlug laptopPlug = new ACtoEuAdapter(euOutlet); laptopPlug.acPlugIn();
…
CIS 3760
Software Engineering
32
acPlugIn()
Common SE problem Adapter Pattern addresses
Problem: An “off the shelf” component offers compelling functionality that you would like to reuse, but its “view of the world” is not compatible with the philosophy and architecture of the system currently being developed.
E.g.: A legacy Rectangle component’s display() method expects to receive “x, y, w, h” parameters, but the client wants to pass
“upper left x and y” and “lower right x and y”. This incongruity can be reconciled with the Adapter pattern
CIS 3760
Software Engineering
33
From https://sourcemaking.com/design_patterns/adapter
Section Outline
Key reuse & object-oriented design concepts
Delegation and inheritance in a sample design pattern
(Adapter)
Types of design patterns & strategies to select & apply design patterns
• Sample patterns – Observer
– Bridge
– Factory Method
– Abstract Factory
CIS 3760
Software Engineering
34
What makes a design modifiable?
• Low coupling and high cohesion • Clear dependencies
• Explicit assumptions
How do design patterns help?
• They are generalized from existing systems
• They provide a shared vocabulary to designers • They provide examples of modifiable designs
– Abstract classes / inheritance – Delegation
CIS 3760
Software Engineering
35
Slides adapted from Bruegge & Dutoit, Pearson
3 Types of Design Patterns
• Structural Patterns
– Reduce coupling between two or more classes
– Introduce abstract classes to enable future extensions
– Encapsulate complex structures
• Behavioral Patterns
– Allow a choice between algorithms and the assignment of
responsibilities to objects (“Who does what?”)
– Characterize complex control flows that are difficult to follow at runtime
• Creational Patterns
– Allow to abstract from complex instantiation processes
– Make the system independent from the way its objects are created, composed and represented.
CIS 3760
Software Engineering
36
Slides adapted from Bruegge & Dutoit, Pearson
Taxonomy of Design Patterns (23 Patterns)
CIS 3760
Software Engineering
37
Slides adapted from Bruegge & Dutoit, Pearson
Eases de
si
gn
b
g Simplifies object creation by
Increases communication
Taxonomy of fDlexeibislityigbyncrePatiangtterns (23 Patterns)
T
simple ways to form
ifyin
common communication controlling how the objects
a
x
o
n
yi
de
o
nt
m
y
entity relationships patterns between entities are created
CIS 3760
Software Engineering
38
Slides adapted from Bruegge & Dutoit, Pearson
Patterns We Will Cover
CIS 3760
Software Engineering
Covered in CIS 3760
Section Outline
Key reuse & object-oriented design concepts
Delegation and inheritance in a sample design pattern
(Adapter)
Types of design patterns & strategies to select & apply design patterns
Sample patterns – Observer
– Bridge
– Factory Method
– Abstract Factory
CIS 3760
Software Engineering
40
Taxonomy of Design Patterns
CIS 3760
Software Engineering
41
Slides adapted from Bruegge & Dutoit, Pearson
Observer Pattern Motivation
• Consider distributed application views that need to maintain up-to-date values for dynamic data from a central application backend (e.g. central database, simulation server)
– E.g. multiple screens in an airport showing up-to-date flight arrivals and departure information
– How does each screen know when the underlying data value has changed in the flights database, and should be updated on the local screen?
CIS 3760
Software Engineering
42
Slides adapted from Bruegge & Dutoit, Pearson
Example Application: Multiple, Supervisory Displays in a UAV Command Centre
Map Display Mission Status Display Remote Assistance Display
Mission Commander Interface
CIS 3760
Software Engineering
43
How can multiple application views maintain up-to-date information?
Two common ways that are used: • Polling
• Publisher-subscriber architecture
CIS 3760
Software Engineering
44
Observer Pattern (aka Publisher-Subscriber Architecture)
CIS 3760
Software Engineering
45
Slides adapted from Bruegge & Dutoit, Pearson
As modeled in Dive into Design Patterns text…
CIS 3760
Software Engineering
46
java.util.Observer example
• https://examples.javacodegeeks.com/core- java/util/observer/java-util-observer-example/
CIS 3760
Software Engineering
47
Where have we seen this Publish- Subscribe / Subject-Observer behaviour before?
Recall the Model-View-Controller Architectural Pattern…
CIS 3760
Software Engineering
49 *from: http://webtechnologyworld.synthasite.com/mvc.php
Taxonomy of Design Patterns
CIS 3760
Software Engineering
50
Slides adapted from Bruegge & Dutoit, Pearson
Problem: De-coupling different aspects that vary or Postponing design decisions to run time
• Many design decisions are made at design time or compile time
• Bridge pattern is useful to delay binding between client and interface implementation until run time (usually in constructor of interface class).
• Bridge pattern also lets you split a large class or a set of closely related classes into two separate hierarchies—abstraction and implementation— which can be developed independently of each other.
RedColor
CIS 3760*from http://javapostsforlearning.blogspot.ca/2012/09/bridge-design-pattern-in-java.html Software Engineering
51
Bridge Pattern
Delegation
Inheritance (optional)
Inheritance
Taxonomy in Application Domain
CIS 3760
Software Engineering
Taxonomy in Solution Domain
Slides adapted from Bruegge & Dutoit, Pearson
52
How do we code this in Java? – see example in BridgePatternExample on CourseLink
Bridge Pattern Example: Different Shapes with Different Color Fills
RedColor
*from http://javapostsforlearning.blogspot.ca/2012/09/bridge-design-pattern-in-java.html
CIS 3760
Software Engineering
53
Continue with Bridge, Let’s Break it Down…
Let’s start with this: Coloured Shapes using inheritance
Shvet, Dive into Design Patterns (Bridge Pattern section) https://www.journaldev.com/1491/bridge-design-pattern-java
“This problem occurs because we’re trying to extend the shape classes in two independent dimensions: by form and by color. That’s a very common issue with class inheritance.” – Shvets, p. 163
CIS 3760
Software Engineering
54
Let’s Implement this instead with the Bridge Pattern…
What is an abstract class in Java? What is an interface in Java?
CIS 3760
Software Engineering
55 https://www.journaldev.com/1491/bridge-design-pattern-java
Bridge Pattern allows multiple implementations under the same interface
• The bridge pattern can be used to provide multiple implementations under the same interface
– Example: Interface to a component that is incomplete, not yet known or unavailable during testing, e.g. multiple database implementations
Arena
imp
LeagueStore
LeagueStoreImplementor
Stub Store Implementor
XML Store Implementor
JDBC Store Implementor
CIS 3760
Software Engineering
56
Slides adapted from Bruegge & Dutoit, Pearson
Adapter vs Bridge
• Similarities:
– Both hide the details of the underlying implementation
• Difference:
– The adapter pattern is geared towards making unrelated components work together
Applied to systems that are already designed (reengineering, interface engineering projects)
“Inheritance followed by delegation”
– A bridge, on the other hand, is used up-front in a design to let abstractions
and implementations vary independently
Green field engineering of an “extensible system”
New “beasts” can be added to the “zoo” (“application and solution domain zoo”), even if not known at design time
“Delegation followed by inheritance”.
CIS 3760
Software Engineering
57
Slides adapted from Bruegge & Dutoit, Pearson
Bridge Case Study – Posted on CourseLink
CIS 3760
Software Engineering
58
Switch to Bridge Activity Slides
59
Reminders/Announcements
• Sprint 1 marks/feedback are available in CourseLink Dropbox: Sprint 1 Marks (Section #)
• You are required to attend non-demo labs to check in with your TA. Please stay in lab until your TA has spoken with your group.
– If you have a conflict, please let the TA know
CIS 3760
Software Engineering
60
Course Checkpoint
• Midterms returned late this week/early next
– Exemplar answers will be released to help you study for final
• Sprint 3 demos / docs /IARs next week (week of Mar 22)
• Easter weekend (Apr 2-4)
• Sprint 4/Final demos / docs / IARs in 3 weeks (week of Apr 5)
– Peer Assessment #2, Scrum Master Assessment, Project Post-Mortems also due that week (Apr 9)
• Take-home final exam released in 5 weeks (Apr 15) – Take-home final exam due Apr 19
CIS 3760
Software Engineering
61
Review: Design Patterns, Adapter, Observer, Bridge
CIS 3760
Software Engineering
62
Eases de
si
gn
b
g Simplifies object creation by
Increases communication
Taxonomy of fDlexeibislityigbynreaPliziangtterns (23 Patterns)
T
a
x
simple ways to realize
o
n
yi
de
o
nt
m
ifyin
common communication controlling how the objects
y
entity relationships patterns between entities are created
CIS 3760
Software Engineering
63
Slides adapted from Bruegge & Dutoit, Pearson
Taxonomy of Design Patterns
CIS 3760
Software Engineering
64
Slides adapted from Bruegge & Dutoit, Pearson
Motivating Encapsulation of Object Creation
https://www.linkedin.com/learning/programming-foundations-design-patterns-2/the-need-for-factory-patterns?u=56996833
Module 7 (The Factory Patterns) of
Programming Foundations: Design Patterns Course (LinkedLearning.com)
CIS 3760
Software Engineering
65
General Problem Addressed by Factory Method and Abstract Factory Patterns
• Want to defer the decision of what specific type of object to create (i.e. instantiate) until runtime
• E.g. you know you want to create some type of lightbulb, interface widget, etc. but you won’t know which type you’ll need until runtime
• The Factory Method Pattern is used to create one product/object only
• The Abstract Factory Pattern is used to create families of related or dependent products/objects
– Abstract Factory Pattern typically uses Factory Methods to accomplish this
CIS 3760
Software Engineering
66
Factory Method Pattern
Problem: Want to defer the decision of what specific type of object to create (i.e. instantiate) until runtime
factory method (abstract method in super class)
factory method
(implemented in concrete class)
CIS 3760
Software Engineering
67 https://dzone.com/articles/design-patterns-factory
Factory Method Pattern Example
Example software design scenario
We are designing a 3D CAD software application to allow home owners to remodel their kitchens, bathrooms, etc.
Users want to see how different light fixtures illuminate their room designs. But different light fixtures take different types of lights (LED, Halogen, etc.), which each have different lighting properties.
We won’t know what type of light we need to model until the user picks a desired light fixture at runtime.
CIS 3760
Software Engineering
68
The Factory Method Pattern can help
LightBulbFactory
createBulb(): LightBulb
orderBulb()
LightBulb
LEDBulb
HalogenBulb
LEDBulbFactory
createBulb()
HalogenBulbFactory
createBulb()
CIS 3760
Software Engineering
runtime dependency
69
The Factory Method Pattern can help
Product
Creator
createBulb():LightBulb
orderBulb(int lumens):LightBulb
LightBulbFactory
LightBulb
Client
factory method
LEDBulb
HalogenBulb
LEDBulbFactory
HalogenBulbFactory
createBulb():
LightBulb
createBulb():
LightBulb
CIS 3760
Software Engineering
runtime dependency
70
In Java Code…
// in Client code (i.e. main)…
if (//halogen fixture) {
LightBulbFactory factory = new HalogenBulbFactory();
LightBulb bulb = factory.orderBulb(800); //800 lumens } else if (//LED fixture) {
LightBulbFactory factory = new LEDBulbFactory();
LightBulb bulb = factory.orderBulb(800); //800 lumens }
// then do stuff with the “bulb”, e.g. illuminate it
CIS 3760
Software Engineering
71
In Java Code…
// in LightBulbFactory / HalogenBulbFactory
public abstract class LightBulbFactory { public LightBulb orderBulb(int lumens) {
LightBulb bulb;
bulb = createBulb(lumens); return bulb;
}
abstract LightBulb createBulb(int lumens); }
public class HalogenBulbFactory extends LightBulbFactory { public LightBulb createBulb(int lumens) {
return new HalogenBulb(lumens);
} }
CIS 3760
Software Engineering
72
Another example (Shvets p. 77, associated code pp. 78-79)
CIS 3760
Software Engineering
73
Now, want if we want to create a whole set of fixtures, or widgets?
CIS 3760
Software Engineering
74
Abstract Factory Pattern Motivation
• Consider a user interface toolkit that supports multiple look and feel standards for different operating systems (e.g. Windows 10, iOS 10):
– How can you write a single user interface and make it portable across the different look and feel standards for these window managers?
• Consider a facility management system for an intelligent house that supports different control systems:
– How can you write a single control system that is independent from the manufacturer?
CIS 3760
Software Engineering
75
Slides adapted from Bruegge & Dutoit, Pearson
Abstract Factory Pattern
CIS 3760
Software Engineering
Slides adapted from Bruegge & Dutoit, Pearson
76
runtime dependency
Applicability for Abstract Factory Pattern
• Manufacturer Independence
– System should be configured with one family of products, where one had to choose from many different families
• Constraints on related products
– Family of related products is designed to be used together and you need to enforce this constraint
• Cope with upcoming change
– Currently using one product family, but expect the underlying technology to change soon as new products appear on market
CIS 3760
Software Engineering
77
Slides adapted from Bruegge & Dutoit, Pearson
Example: A Facility Management System for a House
HouseFactory
createBulb()
createBlind()
IntelligentHouse
EIBFactory
createBulb()
createBlind()
LightBulb
LuxmateFactory
createBulb()
createBlind()
Blind
EIBBulb
LuxmateBulb
EIBBlind
LuxmateBlind
CIS 3760
Software Engineering
78
runtime dependency
Example: A Facility Management System for a House
HouseFactory
createBulb()
createBlind()
IntelligentHouse
EIBFactory
createBulb()
createBlind()
LightBulb
LuxmateFactory
createBulb()
createBlind()
Blind
EIBBulb
LuxmateBulb
EIBBlind
LuxmateBlind
CIS 3760
Software Engineering
79
runtime dependency
Let’s come back to the UI widgets problem…
• Consider a user interface toolkit that supports multiple look and feel standards for different operating systems (e.g. Windows 10, iOS 10):
– How can you write a single user interface and make it portable across the different look and feel standards for these window managers?
CIS 3760
Software Engineering
80
Activity: A UI Standards Manager for different OS Platforms… In-class activity with handout
HouseFactory
createBulb()
createBlind()
IntelligentHouse
EIBFactory
createBulb()
createBlind()
LightBulb
LuxmateFactory
createBulb()
createBlind()
Blind
EIBBulb
LuxmateBulb
EIBBlind
LuxmateBlind
CIS 3760
Software Engineering
81
runtime dependency
Activity: A UI Standards Manager for different OS Platforms… In-class activity with handout
UIStandardsMgr
Application
CIS 3760
Software Engineering
82
runtime dependency
In code, this UIStandardsMgr would work like this: (also see code example in Shvets, pp. 96-98)
if (// Mac OS) {
UIStandardsMgr factory = new MacOSXFactory(); Button button = factory.createButton();
Scrollbar scrollbar = factory.createScrollbar();
…
} else if (// Windows OS 10) { …
}
// use button and scrollbar to create your interface. If UI standards change over time, this code doesn’t change, but your factory does
CIS 3760
Software Engineering
83
More on Factory Method vs. Abstract Factory Patterns
• Abstract Factory pattern uses composition to delegate responsibility of creating object to another class
while Factory Method design pattern uses inheritance and relies on derived class or sub class to create object.
• Factory Method pattern allows for the case where a client doesn’t know what concrete classes will be required to create at runtime, but just wants to get a class that will do the job
• Abstract Factory pattern is best utilised when your system has to create multiple families of products or you want to provide a library of products without exposing the implementation details
CIS 3760
Software Engineering
Adapted from http://stackoverflow.com/questions/5739611/ 84 differences-between-abstract-factory-pattern-and-factory-method
Taxonomy of Design Patterns (23 Patterns)
CIS 3760
Software Engineering
85
Slides adapted from Bruegge & Dutoit, Pearson
Clues for Selecting Some Design Patterns
• Text: “manufacturer independent”, “device independent”,
“must support a family of products” => Abstract Factory Pattern
• Text: “must interface with an existing object” => Adapter Pattern
• Text: “must interface to several systems, some of them to be developed in the future”,
“ an early prototype must be demonstrated” =>Bridge Pattern
CIS 3760
Software Engineering
86
Slides adapted from Bruegge & Dutoit, Pearson
Clues for Selecting Some Design Patterns (2)
• Text: “must be extensible”, “must be scalable”
=> Observer Pattern (MVC Architectural Pattern)
• Text: “must defer/delay creation of specific objects until runtime”
=> Factory Method Pattern
CIS 3760
Software Engineering
87
Slides adapted from Bruegge & Dutoit, Pearson
Summary
• Adapter, Bridge (Structural Patterns)
– Focus: Composing objects to form larger structures
Realize new functionality from old functionality, Provide flexibility and extensibility
• Observer (Behavioral Pattern)
– Focus: Algorithms and assignment of responsibilities to objects
Avoid tight coupling to a particular solution
• Factory Method / Abstract Factory (Creational Pattern)
– Focus: Creation of complex objects
Hide how complex objects are created and put together
CIS 3760
Software Engineering
88
Slides adapted from Bruegge & Dutoit, Pearson
Summary
•
Design patterns are template solutions for common design problems
such as
– separating an interface from a number of alternate implementations
– Accessing a set of legacy classes
– protecting a caller from changes associated with specific platforms
A design pattern consists of a small number of classes
– uses delegation and inheritance
– provides a modifiable design solution
These classes can be adapted and refined for the specific system under construction
– To provide the reuse of existing solutions
– Customization of the system.
• •
CIS 3760
Software Engineering
89
Slides adapted from Bruegge & Dutoit, Pearson
Required Readings from
“Dive into Design Patterns” by A. Shvets
• Shvets pp. 23-28 (Intro to design patterns) – basics concepts of design patterns
• Shvets pp. 29-47 (S/W design principles) – code reuse, extensibility, encapsulation, programming to an interface, composition (or delegation) vs. inheritance
– Optional reading: SOLID principles (pp. 48-67)
• Shvets pp. 68-70 (Catalogue of Design Patterns)
• Shvets pp. 71-102 (Factory Method & Abstract Factory patterns)
• Shvets pp. 146, 149-161 (Adapter pattern)
• Shvets pp. 146, 162-176 (Bridge pattern)
• Shvets pp. 248, 336-351 (Observer pattern)
CIS 3760
Software Engineering
90
Additional (Optional) Readings
• E. Gamma et.al., Design Patterns, 1994.
• M. Fowler, Analysis Patterns: Reusable Object Models, 1997
• F. Buschmann et. Al., Pattern-Oriented Software Architecture: A System of Patterns, 1996
• T. J. Mowbray & R. C. Malveau, CORBA Design Patterns, 1997
• S. W. Ambler, Process Patterns: Building Large-Scale Systems Using Object Technology, 1998.
• Dependency management: P. Feiler & W. Tichy, “Propagator: A family of patterns,” in Proceedings of TOOLS-23’97, Santa Barbara, CA, Aug, 1997.
• Configuration management: W. J. Brown et. Al., AntiPatterns and Patterns in Software Configuration Management, 1999.
CIS 3760
Software Engineering
91
Slides adapted from Bruegge & Dutoit, Pearson online resources
Additional Materials (Optional)
92
Different Uses of Inheritance
• Inheritance is used to achieve two different goals 1. Description of taxonomies
2. Interface specification
1. Identification of taxonomies
– Used during high-level design & analysis phase of SE (i.e. in “design” activity)
– Activity: identify domain objects that are hierarchically related
– Goal: make the system design more understandable
CIS 3760
Software Engineering
93
Slides adapted from Bruegge & Dutoit, Pearson
Different Uses of Inheritance (cont’d)
2. Interface specification
– Used during detailed design phase of SE (i.e. when approaching “implementation” activity)
– Activity: identify abstract classes and common behaviors
– Goal: increase reusability, enhance modifiability and extensibility
Inheritance is found either by specialization or generalization
CIS 3760
Software Engineering
94
Slides adapted from Bruegge & Dutoit, Pearson
Implementation Inheritance
•
A very similar class is already implemented that does almost the same as the desired class implementation.
List
Add ()
Remove()
Example: I have a List class, I need a Stack class.
How about subclassing the Stack class from the List class and providing three methods, Push() and Pop(), Top()?
“Already implemented”
Stack
Push()
Pop()
Top()
Problem with implementation inheritance:
Some of the inherited operations might exhibit unwanted behavior.
What happens if the Stack user calls Remove() instead of Pop()?
CIS 3760
Software Engineering
95
Slides adapted from Bruegge & Dutoit, Pearson
Metamodel for Inheritance
• Inheritance is used during analysis and system design
Inheritance
Detailed Design/ Implementation
High-level Design
Taxonomy
Inheritance
for Reuse
Inheritance detected
by specialization
Inheritance detected
by generalization
CIS 3760
Software Engineering
96
Slides adapted from Bruegge & Dutoit, Pearson
Specification
Inheritance
Implementation
Inheritance
Activity: Implementation or Specification Inheritance?
• Rectangle class inherits from Polygon class – Specification
• Set class inherits from BinaryTree class – Implementation
• Player class inherits from User class – Specification
• Window class inherits from Polygon class – Implementation
CIS 3760
Software Engineering
97
Slides adapted from Bruegge & Dutoit, Pearson
Delegation (or Composition): As Alternative to Implementation Inheritance
• Delegation is a way of making aggregation/composition as powerful for reuse as inheritance
• In delegation two objects are involved in handling a request
– A receiving object delegates operations to a delegate object
– The developer can make sure that the receiving object does not allow the client to misuse the delegate object
delegates to
Client
calls
Receiver
Delegate
CIS 3760
Software Engineering
98
Slides adapted from Bruegge & Dutoit, Pearson
Taxonomy of Design Patterns
Revisiting Bridge
CIS 3760
Software Engineering
111
Slides adapted from Bruegge & Dutoit, Pearson