Nothing Special   »   [go: up one dir, main page]

cs603 Handouts 001-082

Download as pdf or txt
Download as pdf or txt
You are on page 1of 729

Software Design and Architecture

Fakhar Lodhi
Topics Covered: 001 – 082
Software Design Concepts
Software Design and
Architecture

Topic#001
Design – What and Why
What is design?
Definition from Cambridge Dictionary

Verb
to make or draw plans for something, for example
clothes or buildings

What is design?
Definition from Cambridge Dictionary
Noun
a drawing or set of drawings showing how a building or
product is to be made and how it will work and look
Dress Design
Product Design
Mechanical Design
Building Elevation Design
Building Floor Plan Design
Landscape Design
Interior Design
Software Design
Software Design
Software Design
Why should structures/systems need to be designed at all?
"You can use an eraser on the drafting
table or a sledgehammer on the
construction site.“
--Frank Lloyd Wright
Software Design and Architecture Topic#001 END!
Software Design and
Architecture

Topic#002
Design – Objectives
The
A "blueprint"
System Software
for
Specification Design
implementation
Process
During the design phase, software engineers apply their knowledge of:
• the problem domain

• implementation technologies
translate system specifications into plans for the technical implementation
of the software
Serves as a technical plan for implementation
Specifies the overall structure and organization of the eventual cod
The system or program should meet customer’s needs
Should be easy to implement
Should be “efficient”
Should be “easily extendible” to meet new needs

Software Design and Architecture Topic#002 END!


Software Design and
Architecture
Topic#003
Software Design – Complexity
Poorly designed programs are difficult to understand and modify

Cost of adding the ith feature to a well-designed and poorly designed program
Topic#003

END!
Software Design and
Architecture
Topic#004
Software Design Complexity and
Size
The size does matter!
The larger the program, the
more pronounced are the
consequences of poor design
Software Design and

Architecture

Topic#004 END!
Software Design and
Architecture
Topic#005
Software Design Types of
Complexities
Two Types of Complexity in Software

Essential complexities – complexities that are inherent


in the problem.
Accidental/incidental complexities – complexities that are
artifacts of the solution.
The total amount of complexity in a software solution is:

Essential Complexities
+
Accidental complexities
Design
An Antidote to Complexity primary tool for
managing essential and accidental complexities in
software
Software Design and

Architecture

Topic#005 END!
Software Design and
Architecture

Topic#006
Why is Software Design Hard?
Why Design is Hard

Design is difficult because design is an abstraction of the solution which has yet to
be created.
Software Design and

Architecture Topic#006 END!


Software Design and
Architecture

Topic#007 Software Design


A science or an art?
Difficulty with design
A Science

An Art
Software Design and

Architecture

Topic#007 END!
Software Design and
Architecture

Topic#008 Software Design a


Wicked Problem
A wicked problem
A problem that can only be
clearly defined by solving it
Design is a wicked problem!

Even those proficient at


software design might not
be able to fully explain
how they arrived at their
result
Software Design and

Architecture

Topic#008 END!
Software Design and
Architecture
Topic#009
How to make the design process
more systematic and
predictable?
The design process can be made more systematic and predictable through the
application of methods, techniques and
patterns, all applied according to principles and heuristics.
Software Design and

Architecture

Toipc#009 END!
Software Design and
Architecture
Topic#010
Role of Modularity, Hierarchical
Organization, Information Hiding, and
Abstraction in dealing with software
complexity
Good design doesn’t reduce the total amount of essential complexity in a solution
but it will reduce the amount of complexity that a programmer has to deal with at
any one time
A good design will manage essential complexities inherent in the problem without
adding to accidental complexities consequential to the solution.
Modularity subdivide the solution into
smaller easier to manage components
(divide and conquer)
Hierarchical Organization larger components may be composed of
smaller components
Information Hiding hide details and complexity behind simple
interfaces
Abstraction use abstractions to suppress
details in places where they are unnecessary
Software Design and

Architecture

Topic#010 END!
Software Design and
Architecture
Topic#011
Characteristics of Software Design

A deterministic process is one that produces the same output given the same
inputs
A Science

An Art
Design is non-deterministic

No two designers or design processes are likely to produce the same output.
Heuristic because design is non-
deterministic, design
techniques tend to rely on
heuristics and rules-of-thumb rather than repeatable processes.
Emergent the final design evolves from
experience and feedback
Design is an iterative and incremental process where a complex
system arises out of relatively simple interactions
Software Design and

Architecture

Topic#011 END!
Software Design and
Architecture
Topic#012 Benefits of Good
Design
Good design reduces software c omplexity - making the software easier to
understand and modify

Rapid development Easier Maintenance


Good design makes it easier to reuse code.
•It improves software quality.
•Good design exposes defects and makes it easier to test the software.

•Complexity is the root cause of other problems such as security. A program that is
difficult to understand is more likely to be vulnerable to exploits than one that is
simpler.
Software Design and

Architecture

Topic#012 END!
Software Design and
Architecture

Topic#013 A Generic Design


Process
The final design evolves from experience and feedback

Design is an iterative and incremental process where a complex


system arises out of relatively simple interactions
1.
Understand the problem (software requirements)
2.
Construct a “black-box” model of solution (system specification).
System specifications are typically represented with use cases
(especially when doing OOD).
3.
Look for existing solutions (e.g. architecture and design patterns) that cover
some or all of the software design problems identified.
4.
Design not complete? Discover missing requirements

Consider building prototypes


5.
Document and review design
6.
Iterate over solution
(Refactor) (Evolve the design until it meets functional requirements and maximizes
non-functional requirements) Software Design and Architecture Topic#013 END!
Software Design and Architecture
Topic#014 Inputs to the design
process
User requirements and
system specification
(including any constraints
on design and
implementation options)
Domain knowledge (For
example, if it’s a
healthcare application the
designer will need some
knowledge of healthcare
terms and concepts.)
Implementation knowledge
(capabilities and limitations
of eventual execution
environment)
Software Design and

Architecture

Topic#014 END!
Software Design and
Architecture
Topic#015
Desirable Internal Design
Characteristics
Poorly designed programs
are difficult to understand
and modify
Ease of maintenance – Your
code will be read more often
then it is written.
Desirable Internal
Design
Characteristics
Minimal complexity
Keep it simple

Maybe you don’t need


high levels of generality.
Extensibility
Design for today but with an
eye toward the future.
Note, this characteristic can be
in conflict with “minimize
complexity”.
Engineering is all
about balancing
conflicting
objectives
Loose coupling
minimize dependencies
between modules
Reusability
Reuse is a hallmark of a
mature engineering
discipline
Portability
works or can easily be made
to work in other
environments
Software Design and

Architecture

Topic#015 END!
Software Design and
Architecture

Topic#016Topic#016
What is good design?
What is good design?
• Is it efficient code?
• compact implementation?
• Most maintainable?

Maintainable Design
• Cost of system changes is minimal
• Readily adaptable to modify existing functionality
and enhance functionality
• Design is understandable
• Changes should be local in effect
High Cohesion and Low

Coupling Software Design and


Topic#016
Architecture Topic#016
END! END!
END!
Software Design and
Architecture

Topic#017
Coupling
Coupling
• Coupling is the measure of dependency between
modules/components.
• The degree of interdependence between two
modules/components
• A dependency exists between two
modules/components if a change in one could
require a change in the other.

Inter-component relationship
Measuring Coupling
• The degree of coupling between modules is
determined by:
• The number of interfaces between modules (quantity)
• Complexity of each interface (determined by the type of
communication) (quality)
Why is high degree of coupling
bad?
• Highly coupled systems have strong interconnection
• High dependence of program units upon one
another • Difficult to test, reuse, and understand
separately
Loosely coupled modules are
less dependent upon each
other and hence are easier to
change
We aim to minimize coupling to
make modules as independent
as possible!
Coupling – How to reduce it?
• Low coupling can be achieve by:
• eliminating unnecessary relationships
• reducing the number of necessary relationships
• easing the ‘tightness’ of necessary relationships
Software Design and

Architecture

Topic#017 END!
Software Design and
Architecture

Topic#018
Coupling – Example
Design of a simple web app
<!doctype html>
<html>
<head>
<script type="text/javascript" src="base.js">
</script>
<link rel="stylesheet" href="default.css">
</head>
<body>
<button </button>
<button </button>
<h1 id="title" class="NormalClass">
CSS <--> JavaScript Coupling
</h1>
</body>
.NormalClass {
color:inherit;
font-style:normal;
}

default.css
<!doctype html>
<html>
<head>
<script type="text/javascript" src="base.js">
</script>
<link rel="stylesheet" href="default.css">
</head>
<body>
<button </button>
<button </button>
<h1 id="title" class="NormalClass">
CSS <--> JavaScript Coupling
</h1>
We want to change the
</body>

style of the title in </html>

response to user action


function highlight() {
document.getElementById("title").
style.color="red";
document.getElementById("title").
style.fontStyle="italic";
}

function normal() {
document.getElementById("title").
style.color="inherit";
document.getElementById("title").
style.fontStyle="normal";
}
Option A
JavaScript code modifies the style attribute of HTML
element.
function highlight() {
document.getElementById("title").
className = "HighlightClass";
}

function normal() {
document.getElementById("title").
className = "NormalClass";
}
Option B
JavaScript code modifies the class attribute of HTML
element.
.NormalClass {
color:inherit;
font-style:normal;
}

.HighlightClass {
color:red; font-
style:italic;
}
default.css
Software Design and

Architecture

Topic#018 END!
Software Design and
Architecture

Topic#019
Cohesion
Cohesion
• Cohesion refers to the degree to which the
elements inside a module belong together
• A measure of the strength of relationship between:
• the methods and data of a class and some unifying
purpose or concept served by that class
• the class’s methods and data themselves
A module has high cohesion if all of its
elements are working towards the same
goal
Cohesion: Intra-component relationship
Low Cohesion High Cohesion
High vs Low Cohesion
Highly Cohesive Modules Lowly Cohesive Modules
• Easier to understand • Difficult to understand
• More Robust • Difficult to maintain
• More Reliable • Difficult to test
• More Reusable • Difficult to reuse
Software Design and

Architecture

Topic#019 END!
Software Design and
Architecture

Topic#020
Relationship between Coupling
and Cohesion
High Cohesion and Low Coupling -
Benefits
Highly Cohesive Modules Lowly Coupled Modules
• easier to read and • easier to read and
understand understand
• Easier to modify • Easier to modify
• Increased potential for • Increased potential for
reuse reuse
• Easier to develop and test • Easier to develop and test

Surprised?
Are they somehow related?
Low Cohesion and High Coupling High Cohesion and Low Coupling
Cohesion and Coupling
• Coupling: Inter-component relationships
• Cohesion: Intra-component relationships

The best designs have high


cohesion within a module and
low coupling between modules
Cohesion and Coupling
Tend to be Inversely Correlated
When Coupling is high, cohesion tends to
be low and vise versa
Software Design and

Architecture

Topic#020 END!
Software Design and
Architecture

Fakhar Lodhi
Topics Covered: 021 – 027
Object-Orientation – Introduction
Software Design and
Architecture

Topic#021
Software Design Strategies
Structured and Object-Oriented
Design
Software Design Strategies
 Structured Design
 Object-Oriented Design
Structured Design
 System is designed from a functional view point
 Conceived as a set of functions that are used to solve the
problem at hand
 The system state is centralized and is shared among the
functions operating on that state
Structured Design
 What the set of
functions/programs should be?
 What each function should
accomplish?
 How functions should be
organized in a hierarchy?
 Start with a high level view and
progressively refine this into more
detailed design
Action-Oriented
Object-Oriented Design
 Based on the idea of information hiding
 System is viewed as a collection of objects
 The system intelligence and state is decentralized and
each object manages its own state information
 Attributes (state) and Operation (intelligence)
 Objects communicate by exchanging messages
Maintainable Design
What? How?
 Cost of system changes is  Low coupling and high
minimal cohesion
 Design is understandable  Self contained components
 Changes should be local in  Close relationship of data
effect and function
Object-Oriented Design
Software Design and
Architecture

Topic#021
END!
Software Design and
Architecture

Topic#022
Object-Orientation Basic Concepts
The Object and The Class
The Object
 An object is a tangible entity that exhibits some well
defined behavior.
 An object represents an individual, identifiable item, unit,
or entity, either real or abstract, with a well defined role
in the problem domain
An object has state, behavior, and identity
The State
 The state of an object is encapsulated within the object.
Current values of the properties of the object
The Behavior
 How an object acts and reacts in terms of its state
changes and message passing
 How it acts and reacts
Part of System Intelligence Delegated to the
Object
The Identity
 Identity is that property of an object which distinguishes
it from all other objects
Who will provide a specific service?
Software Design and
Architecture

Topic#022
END!
Software Design and
Architecture

Topic#023
Object-Orientation Basic Concepts
The Class
The Class
 Represents similar objects
 Its instances
Template of an object
Properties and Behavior
The Class
 A class represents an abstraction
 Specifies an interface ( the outside view - the public part)
 What can I do for you?
 declaration of all the operations applicable to instances of this class
 Defines an implementation (the inside view - the private part)
 How is it actually done?
 The structure – how the information is maintained
 The implementation of the operations declared in the interface
 How a task is performed – the algorithm
Software Design and
Architecture

Topic#023
END!
Software Design and
Architecture

Topic#024
Object-Orientation Basic Concepts
Relationship between Classes and
Objects - Association
Relationship between Classes
 Classes and Objects – two building blocks of the system
 Behavior of the system is defined by the manner in which
the objects interact with one another
 In order to construct a software system, we need
mechanisms that create connections between these
building blocks
 Association
 Inheritance
Association
 Indicates that the objects of the two classes are related in
some non-hierarchical way
 Implies that an object of one class is making use of an
object of another (or same) class
 Indicated simply by a solid line connecting the two class
icons.
Association
 Does Not imply that there is always a link between all
objects of one class and all objects of the other
 Does imply that there is a persistent, identifiable
connection between two classes.
Conceptual (between classes) as well as
physical (between objects) relationship
Attributes of Associations
 Descriptive name
 arity of the connection
 Direction
 Roles
Software Design and
Architecture

Topic#024
END!
Software Design and
Architecture

Topic#025
Object-Orientation Basic Concepts
Relationship between Classes and Objects
Aggregation and Composition
Aggregation
 A form of association that specifies a whole-part
relationship between an aggregate (a whole) and a
constituent part
 Indicated by a “hollow” diamond
Aggregation
 Most experts have downplayed the importance of general
form of aggregation as not something that deserves to be
embellished in any way
Think of it as a modeling placebo!
Composite Aggregation
 Also known as Composition
 has been recognized as being significant
 Implies that each instance of the part belongs to only one
instance of the whole, and that the part cannot exist
except as part of the whole.
 Composition is indicated with a filled-in diamond
Software Design and
Architecture

Topic#025
END!
Software Design and
Architecture

Topic#026
Object-Orientation Basic Concepts
Relationship between Classes and Objects
Inheritance
Classification and Hierarchy
 Classification of objects into groups of related
abstractions
Inheritance
 Represents a hierarchy of abstraction in which one class
inherits from one or more super-classes.
 One class shares the structure or behavior defined in one
or more classes.
 A subclass augments or redefines the existing structure
and behavior of its super-class.
Generalization/Specialization hierarchy
Inheritance Hierarchy
 Show the relationships among superclasses and
subclasses
 A triangle shows a generalization
Inheritance
 The implicit possession by all subclasses of features
defined in its superclasses
 The implicit possession by all subclasses of features
defined in its superclasses
The Isa Rule
Software Design and
Architecture

Topic#026
END!
Software Design and
Architecture

Topic#027
Object-Orientation Basic Concepts
Abstract Classes and Interfaces
Abstract Class
 When we write a class, we code every field and method;
in other words, the code is complete in a sense
 Sometimes, we might know the specifications for a class,
but might not have the information needed to implement
the class completely
 In such cases, we can implement a class partially using
what are called abstract classes.
Abstract Class
 It provides a basic implementation that other classes can
inherit from
 An instance of the abstract class cannot be created
Interface
 A mechanism to achieve abstraction
 A collection of abstract methods
 No state or implementation
Interface vs Abstract Class
 Abstract classes can be inherited
 A class that implements an
without implementing the
interface must provide an
abstract methods (though such a
implementation of all the
derived class is abstract itself)
methods of that interface
 Abstract classes may contain
 Interfaces can have no state or
state (data members) and/or
implementation
implementation (methods)
As general OO terms, the differences are not
necessarily well-defined.
Software Design and
Architecture

Topic#027
END!
Topic#028 Relationships – Basic Concepts Object Oriented
Programming Defined
OOP as defined by Grady Booch
A method of implementation in which
programs are organized as cooperative
collections of objects, each of which
represents an instance of some class,
and whose classes are all members of a
hierarchy of classes united via inheritance
relationships. 3
Relationships
• Hierarchy of classes
• Inheritance - relationship among classes
• Cooperative collections of objects
• Association - relationship among instances of classes

Object and Class Relationships


End - Object Oriented Programming Defined 4
Software Design and

Architecture

Topic#028 END!
Software Design and
Architecture
Topic#029
Relationships – Basic Concepts
Association
Association
An association is a relationship
among two or more specified
classifiers that describes
connections among their
instances.
Association
•Associations are the “glue” that
holds together a system.
•Without associations, there is
only a set of unconnected
classes.
Types of Association
•Uses Relationship
•Simple Association
•Whole-Part Relationship
•Aggregation
•Composition
UML Object Model Notation
super class
Association
class name

attribute name
Class 1 Class
Operation
Attribute 1 Attribute : name
0..*
Operation 1a Operation :
Operation 1b
subclass
name

Multipicity of
association
Class 5 Class 2 Class 3 Class 4
1
Attribute 5a Attribute 2a Attribute 3a 1+ Attribute 4a
Attribute 2b Attribute 4b

Operation 5a Operation 2 Operation 3a Operation 4


Operation 5b

Composition Inheritance Aggregarion


Software Design and

Architecture

Topic#029 END!
Software Design and
Architecture
Topic#030 Relationships – Basic
Concepts Aggregation and
Composition
Aggregation
A form of association that
specifies a whole-part
relationship between an
aggregate (a whole) and a
constituent part.
Aggregation
The distinction between
aggregation and association is
often a matter of taste rather
than a difference in semantics.
Aggregation
Think of it as a modeling placebo
“Aggregation is strictly
meaningless; as a result, I
recommend that you ignore it in
your own diagrams”
Aggregation
UML Distilled by Martin Fowler
Composition
A form of aggregation association
with strong ownership and
coincident lifetime of parts by
the whole Composition
A form of aggregation association
with strong ownership and
coincident lifetime of parts by
the whole
End – Aggregation and Composition
Software Design and

Architecture

Topic#030 END!
Software Design and
Architecture
Topic#031
Object Lifetime and Visibility
Inheritance
Inheritance
•B inherits from A
•A is the super or base class and B is the
sub or derived class
•A does not know about B ⚫When an
object of Type B is created, a
corresponding object of Type A is
also created
⚫Conceptually speaking, the object of
Type B holds the corresponding
object of Type A as a private
component.
For example, when an object, say
b2, of Type B is created, another
object, say a5, of Type A is also
b2

a5
created.
⚫a5 is only accessible from b2.
⚫exclusive holding
⚫The life of a5 is dependent
b2
upon b2.
⚫a5 is created with b2 and it
dies with b2. a5
⚫Cardinality of this relationship
is 1:1
End of topic
Software Design and

Architecture

Topic#031 END!
Software Design and
Architecture
Topic#032
Object Lifetime and Visibility
Composition
Composition
•Whole-part relationship
•B has many instances of A
•B is the container or whole, A is the
part.
•A does not know about B
Composition
•A form of aggregation association
with strong ownership and
coincident lifetime of parts by the
whole.
•A part may belong to only one
composite.
Composition
•Parts with non-fixed multiplicity may be
created after the composite itself.
•Once created, they live and die with it
(that is, they share lifetimes).
•Such parts can also be explicitly removed
before the death of the composite.
Composition – object creation and life-time
 When an object of Type B is created, corresponding
instances of Type A are also created
 Conceptually speaking, the object of
Type B holds the corresponding objects b2
of Type A as private components.
 For example, when an object, say b2, of a5 a6
Type B is created, some objects of Type
A, say a5 and a6, are also created.
Composition – object creation and life-time
 a5 and a6 are only accessible from b2.
 exclusive holding

 The life of a5 and a6 is dependent


b2
upon b2. a5 a6
 a5 and a6 are created with b2 and
destroyed with b2. ⚫Cardinality of
this relationship
could be 1:1 or 1:m End of topic
Software Design and

Architecture

Topic#032 END!
Software Design and
Architecture
Topic#033
Object Lifetime and Visibility
Association
Association – some sort of link
between objects
•One instance of B is associated with
many instances of A
Association – object creation and life-
time
⚫Objects of the two types
have independent life b2
times.
⚫Conceptually speaking,
objects of Type B are a5 a6
Association – object creation and life-
time
b2
linked with objects of
Type A. a5 a6
⚫The relationship is not
exclusive. That is, the b3
same instance of A may
a7
Association – object creation and life-
time
also be linked and
accessed directly by
other objects.
⚫Cardinality of this
Association – object creation and life-
time
relationship could be 1:1,
1:m, or m:m
Association – object creation and life-
time
End of topic
Software Design and

Architecture

Topic#033 END!
Software Design and
Architecture
Topic#034
Object to Relational Mapping
Basics
● Relational Database
● Objects
● Mapping between Objects & Relational Database
O2R Mapping

•aka – O2R, ORM, O/RM, and O/R

•Mapping attributes
•Mapping Inheritance
•Mapping Association
•Mapping Composition End of topic
40
Software Design and

Architecture

Topic#034 END!
Software Design and
Architecture
Topic#035 Object to Relational
Mapping Mapping Inheritance
Mapping Inheritance
A
•Filtered Mapping
id_a
•Horizontal a1
Mapping
•Vertical Mapping B C
Filtered Mapping id_b id_c
b1 c1
246
TableName
•All the classes of an a_id
inheritance hierarchy are a1
b_id
mapped to one table. b1
Horizontal Mapping c_id
c1

247
•Each concrete class is TableForB
a_id a_id
TableForC mapped to a a1
a1
separate table and each b_id c_id
such table includes the b1 c1
attributes and the inherited attributes of the
class that it is representing.
End of topic

248
Software Design and

Architecture

Topic#035 END!
Software Design and
Architecture
Topic#036 Object to Relational
Mapping Mapping Inheritance –
Vertical Mapping
Vertical Mapping TableForA
•Each class of the inheritance a_id
hierarchy, whether abstract a1 or
concrete, TableForB TableForC is
mapped to a separate
table. a_id (FK) a_id (FK)
b_id b1 c_id c1
48
Vertical Mapping TableForA
a_id
•To maintain the inheritance a1
relationship between parent
and child TableForB TableForC
classes, OID of the
a_id (FK) a_id (FK)
b_id b1 c_id c1
parent class is inserted in the child classes as
a foreign key.
49

Vertical Mapping Example


Vertical Mapping Example
oid_a u v oid_b oid_a(FK) x y
10 23 10 1 21 567 100
21 34 54 2 10 98 43
35 78 17 3 35 718 127

⚫For example, object of type B with oid_b


= 3 contains object of type A with
oid_a = 35 End of topic
Software Design and

Architecture

Topic#036 END!
Software Design and
Architecture
Topic#037
Object to Relational Mapping
Mapping Composition
⚫each class of the whole-part hierarchy is mapped
to a separate table.
⚫To maintain the whole-part relationshipbetween
the whole (composite class) and the part
(component class), primary key (OID) of the
composite class is inserted in the part classes as
a foreign key.
⚫note
the difference between
composition and inheritance
Composition – Persistence -
Example
Composition – Persistence - Example
oid_b u v oid_a oid_b(FK) x y
10 23 10 1 21 567 100
21 34 54 2 21 98 43
35 78 17 3 35 718 127

⚫Forexample, object of type B with oid_b = 21


contains objects of type A with oid_a = 1 and
oid_a = 2 End of topic
Software Design and

Architecture

Topic#037 END!
Software Design and
Architecture
Topic#038 Object to Relational
Mapping Mapping Association
⚫Eachclass involved in the relationship
is mapped to a separate table.
⚫Tomaintain the relationshipbetween
the classes, primary key (OID) of the
user class is inserted in the classes that
have been used as a foreign key.
⚫Note that, in the OO world, the client knows
the identity of the server whereas in the
relational world, the table for server holds
the identity of the client.
⚫For many-t-many relationship a separate
table is used to maintain the information
about the relationship.
Association – Persistence
Composition – Persistence - Example
oid_b u v oid_a oid_b(FK) x y
10 23 10 1 21 567 100
21 34 54 2 21 98 43
35 78 17 3 35 718 127

⚫Forexample, object of type B with oid_b = 21


uses objects of type A with oid_a = 1 and
oid_a = 2 End of topic
Software Design and

Architecture

Topic#038 END!
Software Design and
Architecture
Topic#039 Object to Relational
Mapping Mapping Cardinality of
Association
One-to-One Relationships
1
Customer Address
1

Customer Table
Address Table
-CustomerOID (PK)
-AddressOID (PK)
-CustomerNumber
275
-House
-AddressOID (FK)
1
-Name 1 -Street
-City
-SSN
One-to-Many Relationships
1
Customer Invoice
*

276
Customer TableInvoice Table
-CustomerOID (PK) -InvoiceOID (PK)
-CustomerNumber -CustomerOID (FK)
-Name 1 * -Date
-SSN -SalesPerson
Many-to-Many Relationships
1..*
Customer Account

277
1..*

Customer Table Account Table


Accesses Table
-CustomerOID (PK) -AccountOID (PK)
-CustomerOID (PK) (FK)
-Name -AccountNumber
-SSN 1 1..* -AccountOID (PK) (FK) 1..* 1 -Balance

278
End of topic

279
Software Design and

Architecture

Topic#039 END!
Software Design and
Architecture
Topic#040
Object to Relational Mapping
Summary
What Life-time Holding / visibility cardinality

Exclusive
Is-a relationship Object of base class is
created and destroyed Parent does not
1:1
parent-child with derived class know about the
relationship object child

Exclusive
Part is created and
whole-part
destroyed with the 1:1, 1:m
relationship Part does not know
whole
about the whole
Non-exclusive
Using relationship
independent 1:1, 1:m, m:m
link Can be one-way or
bi-directional
End of topic
Software Design and

Architecture

Topic#040 END!
Software Design and
Architecture
Topic#041 OOP – Inheritance and
Polymorphism
class Polygon {
protected:
int width, height;
public:
Polygon (int a, int b) : width(a), height(b) {}
virtual int area (void) =0; void printarea()
{ cout << this->area() << '\n'; }
287
};
class Rectangle: public Polygon {
public:
Rectangle(int a,int b) : Polygon(a,b) {}
int area()
{ return width*height; }
};
288
class Triangle: public Polygon {
public:
Triangle(int a,int b) : Polygon(a,b) {}
int area()
{ return width*height/2; }
};
int main () {
289
Polygon * ppoly1 = new Rectangle (4,5);
Polygon * ppoly2 = new Triangle (4,5);
ppoly1->printarea(); ppoly2-
>printarea(); delete ppoly1; delete
ppoly2;
return 0;
}
290
Questions
•What do we gain by using the base class
in the declaration
Polygon * ppoly1 = new Rectangle (4,5);
Polygon * ppoly2 = new Triangle (4,5);
•Why not
291
Rectangle * ppoly1 = new Rectangle (4,5);
Triangle * ppoly2 = new Triangle (4,5);
int main () {
Polygon * ppoly[10]; ppoly[0]
= new Rectangle (4,5);
ppoly[1] = new Triangle (4,5);
// and so on for (int i = 0; i <
10; i++) ppoly[i]-
292
>printarea(); // rest of the
code
return 0;
} End of topic

293
Software Design and

Architecture

Topic#041 END!
Software Design and
Architecture
Topic#042
OOP – Object Creation and Factory Method
int main () {
Polygon * ppoly[10]; ppoly[0]
= new Rectangle (4,5);
ppoly[1] = new Triangle (4,5);
// and so on for (int i = 0; i < 10; i++) ppoly[i]-
>printarea(); // rest of the code
return 0;
} Object creation is
not polymorphic
296
Object creation and Factory Method
Polygon * createPolygon(char t, int w, int h) {
if (t == ‘R’)
return new Rectangle(w, h);
else if (t == ‘T’) return new
Triangle(w, h);
297
}
int main () { Polygon *
ppoly[10]; for (int i = 0; i
< 10; i++) {
// get type, width, and height of the object
// to be created ppoly[i] =
createPolygon(t, w, h);
// pseudo polymorphic behavior

298
} for (int i = 0; i < 10; i++)
ppoly[i]->printarea(); //
rest of the code return 0;
} End of topic

300
Software Design and

Architecture

Topic#042 END!
Software Design and
Architecture
Topic#043
OOP – The Magic Behind Polymorphism
•Compiler maintains two things:
vtable: A table of function pointers. It
is maintained per class.

vptr: A pointer to vtable.


It is maintained per object.

303
VTables

&Rectangle ::printArea
&Rectangle ::draw
Actual Objects
&Rectangle ::rotate
Triangle Object .
.
Array of vptr
.
Polygons
0 Rectangle Object &Triangle ::printArea
1 vptr &Triangle ::draw
&Triangle ::rotate
2
.
. Triangle Object .
vptr .
.
. . . 304

.
•Compiler adds additional code at two
places to maintain and use vptr.
•Code in every constructor. This code sets
vptrof the object being created. This
code sets vptr to point to vtable of the
class.
•Code with polymorphic function call.
305
•Wherever a polymorphic call is
made, compiler inserts code to
first look for vptr.
•Once vptr is fetched, vtable of
derived class can be accessed.
306
Using vtable, address of derived
class.
End of topic

307
Software Design and

Architecture

Topic#043 END!
Software Design and
Architecture

309
Topic#044 OOP – Implementing
Composition
Event

Date Time
311
class Time
{
public:
Time();
Time(int, int);
// some setters, getters, and utility functions
void printTime();
private:
int hr;
312
int min;
};
class
Date {
public:
Date();
Date(int, int, int);
// some setters, getters, and utility functions
void printDate();
private:
313
int month;
int day;
int year;
};
class Event {
public:
Event(int hours = 0, int minutes = 0, int m = 1,
int d = 1, int y = 1900, string name =
“Start of 20th Century");

314
// setters, getters, and other utility functions
void printEventData();
private:
string eventName;
Time eventTime;
Date eventDay;
};

315
int main()
{
//instantiate an object and set data for Eid prayer
Event eidPrayer(6, 30, 12, 8, 2019, “Eid Prayer”);
eidPrayer.printEventData();

//print out the data for object


//instantiate the second object
Event independenceDay(8, 0, 14, 8, 2019,
“National Anthem”);

independenceDay.printEventData();
//print out the data for the second object

return 0;
}
Event::Event(int hours, int minutes, int
m, int d, int y, string name)
: eventTime(hours, minutes),
eventDay(m, d, y)
{
eventName = name;
}
void Event::printEventData()
{
cout << eventName << " occurs
"; eventDay.printDate(); cout <<
" at "; eventTime.printTime();
cout << endl;
}
End of topic

Software Design and

Architecture

Topic#044 END!
Software Design and
Architecture
Topic#045 OOP – Inheritance vs
Composition
Derived_class_name::
Derived_class_constructor_name(types and parameters):
base_class_construcor_name(parameters)
{ set parameters which are not set by the base
class constructor;
}
Aggregate_class_name::
Aggregate_class_construcor_name(types and params):
component_class_instance(parameters)
{ set parameters which are not set by the component
class constructor;
}

•The main advantage inheritance has over


composition is that it allows objects of the
derived class to be dynamically bound in
the same hierarchy as its base classes.

•It is also necessary where virtual methods


must be overridden by the derived class
•a composite aggregate cannot do this.
End of topic

Software Design and

Architecture

Topic#045 END!
Software Design and
Architecture
Topic#046
OOP – Implementing Uni-directional Associations
Example – Lecturer-Course Relationship
•A lecturer may be assigned a course to
teach. That lecturer may be removed
from that course at anytime.

Unidirectional: lecturer is added to the


course and not vice-versa
class course
{
private:
lecturer * L // L is a pointer to an
// object of type lecturer
public:
course();
void addlecturer(Lecturer *);
void removelecturer();
};
Lecturer and course are created separately and then linked
together.

void course::addlecturer(Lecturer *teacher)


{
L = teacher;
}
void course::removelecturer()
{
L = NULL;
}
End of topic
Software Design and

Architecture

Topic#046 END!
Software Design and
Architecture
Topic#047
OOP – Implementing Bi-directional Associations
•Example:
•A lecturer can be added to the course
and vice versa
•In a bi-directional associations both
classes must include a reference(via
a pointer) to the linked object.

•Problem: User has to update both


ends of the relationship.
•Can be achieved by using the operator
this.
void course::addlecturer(lecturer *teacher)
{
L = teacher;
L -> addcourse(this);
}
void lecturer::addcourse(course *subject)
{
C = subject;
}
void main()
{
course * SE101 = new course(…);
lecturer *Fakhar = new lecturer(…);
SE101->addlecturer(Fakhar);
// the association is updated for both objects.
}

N:M associations are implemented using arrays of


pointers from one class to another.
What would happen if it could be added from
either side?
void main()
{ course * SE101 = new course(…);
lecturer *Fakhar = new lecturer(…);

Fakhar->addcourse(SE101);
}
void course::addlecturer(lecturer *teacher)
{
L = teacher;
L -> addcourse(this);
}

void lecturer::addcourse(course *subject)


{
C = subject;
C -> addlecturer(this);
}
Simple – Isn’t it?
void course::addlecturer(lecturer *teacher)
{
if (L == NULL) {
Control the infinite
L = teacher;
L -> addcourse(this); recursion
}
}
void lecturer::addcourse(course *subject)
{ if (C == NULL) {
C = subject;
C -> addlecturer(this);
}
}
void main()
{
course * SE101 = new course(…);
lecturer *Fakhar = new lecturer(…);
SE613->addlecturer(Fakhar);
// or
// Fakhar->addcourse(SE101);

}
End of topic
Software Design and

Architecture

Topic#047 END!
Software Design and
Architecture
Topic#048
SOLID Design Principles - Introduction
A good design will manage
essential complexities
inherent in the problem
without adding to accidental
complexities consequential to
the solution.
Maintainable Design
 Cost of system changes is minimal
 Readily adaptable to modify existing functionality and
enhance functionality
 Design is understandable
 Changes should be local in effect
 Design should be modular
Goal: low coupling and high cohesion
S.O.L.I.D. Design Principles
•Intended to make software designs
more
• Understandable
• Flexible
• Maintainable
SOLID Principle - History
•Originally gathered
by Robert C. Martin
(aka Uncle Bob)

Robert C. Martin
SOLID Principle - History

•Arranged by Michael Feathers into


an easily remembered, albeit ironic,
mnemonic: SOLID.
S.O.L.I.D.
Principle Objective
Single Responsibility Principle (SRP) Increased Cohesion

Open-Closed Principle (OCP) Flexibility, reusability, and maintainability

Liskov Substitution Principle (LSP) Proper Inheritance

Deals with non-cohesive interfaces for


Interface Segregation Principle (ISP)
reducing coupling
Creation of reusable frameworks
Dependency Inversion Principle (DIP)
Reduce inter-module coupling
Software Design and
Architecture

Topic#048
END!
Software Design and
Architecture
Topic#049
SOLID Design Principles
Single Responsibility Principle (SRP)
Single Responsibility Principle (SRP)

A class should have only one reason to change


• Cohesion
• Defined as the functional relatedness of the
elements of a module

• Related to the forces that cause a module, or a


class, to change
Responsibility - a reason for change

•What a class does


•The more a class does, the more
likely it will change
•The more a class changes, the more
likely we will introduce bugs
SRP – Coupling and Cohesion

• If a class has more than one responsibility


• Low cohesion
• High coupling - the responsibilities become
coupled
• Changes to one responsibility may impair or
inhibit the class's ability to meet the others
• Leads to fragile designs that break in unexpected
ways when changed
SRP
• One of the simplest of the principles but one of
the most difficult to get right.

• Finding and separating conjoined responsibilities


is much of what software design is really about

• The rest of in one way


the
principles
come
back to
this issue
or
another
Software Design and
Architecture

Topic#049
END!
Software Design and
Architecture
Topic#050
SOLID Design Principles
Single Responsibility Principle (SRP) - Example
class Post
{
void CreatePost(Database db, string postMessage)
{
try
{
db.Add(postMessage); Create a new post
}
catch (Exception ex)
{
db.LogError("An error occured: ", ex.ToString()); Log Error
File.WriteAllText("\LocalErrors.txt", ex.ToString());
}
}
} Multiple Responsibilities
class ErrorLogger
{
void log(string error)
{
db.LogError("An error occured: ", error);
File.WriteAllText("\LocalErrors.txt", error);
}
}

Class for handling error logging


class Post
{
private ErrorLogger errorLogger = new ErrorLogger();

void CreatePost(Database db, string postMessage)


{
try
{
db.Add(postMessage); create a new post
}

{
catch (Exception ex)
Log Error
errorLogger.log(ex.ToString());
}
delegated using abstraction
}
} Single Responsibility!
Software Design and
Architecture

Topic#050
END!
Software Design and
Architecture
Topic#051
SOLID Design Principles
Open-Closed Principle (OCP)
The Open-Closed Principle (OCP)
• Coined by Bertrand Meyer:

• A software artifact should be open for extension


but closed for modification.
The behavior of a software artifact ought
to be extendible, without having to modify
that artifact.
The Open-Closed Principle (OCP)
• Not simply a principle that guides in the
design of classes and modules.
• Fundamental to good architectural design
If simple extensions to the requirements
force massive changes to the software, then
the architects of that software system have
engaged in a spectacular failure.
• Modules that conform to the open-closed principle
have two primary attributes.
• They are “Open For Extension”.
• We can make the module behave in new and different
ways as the requirements of the application change, or
to meet the needs of new applications.
• They are “Closed for Modification”.
• The source code of such a module is inviolate.
• No one is allowed to make source code changes to it.
• Open-Close - Are these two attributes are at
odds with each other?

• The normal way to extend the behavior of a


module is to make changes to that module.

• A module that cannot be changed is


normally thought to have a fixed behavior.
• How can these two opposing attributes be
resolved?
Extension through
inheritance, composition,
and association
Software Design and
Architecture

Topic#051
END!
Software Design and
Architecture
Topic#052
SOLID Design Principles
Open-Closed Principle (OCP) - Example
class Post }
{
What
void CreatePost(Database db, string postMessage)
{
Happens if
if (postMessage.StartsWith("#")) we had to
{
db.AddAsTag(postMessage); add
}
else
{
db.Add(postMessage);
}
}
Otherwise

Case for # a case for @


Violates OCP
class Post class TagPost
{ {
void CreatePost(Database db, override void CreatePost(Database db,
string postMessage) string postMessage)
{ {
db.Add(postMessage); db.AddAsTag(postMessage);
} }
} }

Now OCP
Compliant
Can easily add a
new post type
Software Design and
Architecture

Topic#052
END!
Software Design and
Architecture
Topic#053
SOLID Design Principles
Liskov’s Substitution Principle (LSP)
Liskov Substitution Principle (LSP)
• Subtypes must be substitutable for their base types.

• Deals with design of inheritance hierarchies


Functions that use references to base
classes must be able to use objects of
derived classes without knowing it.
All dogs know how to wag their
tails.

DogNoWag is a special type of


dog.
DogNoWag does not know how
to wag its tail.
Ignoring the functionality defined in the
base class is violation of LSP
36
Software Design and
Architecture

Topic#053
END!
Software Design and
Architecture
Topic#054
SOLID Design Principles
Liskov’s Substitution Principle (LSP) - Example
class Rectangle
{
public:
virtual void SetWidth(double w) {itsWidth=w;}
virtual void SetHeight(double h) {itsHeight=w;}
double GetHeight() const {return itsHeight;}
double GetWidth() const {return itsWidth;}
private:
double itsWidth;
double itsHeight;
};
class Square : public Rectangle By setting the width
{
of a Square object, its
public:
virtual void SetWidth(double w); height will change
virtual void SetHeight(double h); correspondingly and
}; vice versa.

void Square::SetWidth(double w) Rectangle::SetWi


{ dth(w);
Rectangle::SetHeight(w); The Square object
}
will remain a
mathematically
proper square
SetHeight will be the same as SetWidth Good? – Not really!
void g(Rectangle& r)
{
r.SetWidth(5);
r.SetHeight(4);
assert(r.GetWidth() * r.GetHeight()) == 20);
}
Works fine for a rectangle
but
assertion error if passed a square!
A violation of LSP!
Software Design and
Architecture

Topic#054
END!
Software Design and
Architecture
Topic#055
SOLID Design Principles
Liskov’s Substitution Principle and Inheritance
The True Meanings of IsA Relationship
Validity is not Intrinsic
•A model, viewed in isolation, cannot
be meaningfully validated.

•The validity of a model can only be


expressed in terms of its clients.
Validity is not Intrinsic
• Square and Rectangle classes viewed in
isolation, appeared to be self consistent and
valid.
• Viewed from a programmer standpoint who
made reasonable assumptions about the
base class, the model broke down.
Validity is not Intrinsic
• When considering whether a particular design is
appropriate or not, one must not simply view
the solution in isolation.
• One must view it in terms of the reasonable
assumptions that will be made by the users of
that design.
What Went Wrong? 3
(W )
• Isn’t a Square a Rectangle?
• Doesn’t the ISA relationship hold?
What Went Wrong? 3
(W )
• No!

• A square might be a rectangle, but a Square


object is definitely not a Rectangle object.
What Went Wrong? 3
(W )
• Why?
• Because the behavior of a Square object is not
consistent with the behavior of a Rectangle object.

• Behaviorally, a Square is not a Rectangle!


And it is behavior that software is really all about!
• The LSP makes clear that in OOD the ISA
relationship pertains to behavior.
• Not intrinsic private behavior, but extrinsic
public behavior;

• behavior that clients depend upon.


Software Design and
Architecture

Topic#055
END!
Software Design and
Architecture
Topic#056
SOLID Design Principles
Interface Segregation Principle (ISP)
Interface Segregation Principle (ISP)
• Clients should not be forced to depend upon interfaces that they do
not use
if you have an abstract class or an interface, then the
implementers should not be forced to implement parts that
they don't care about.
Interface Segregation Principle (ISP)
In programming, the interface segregation principle states that no
client should be forced to depend on methods it does not use.

Put more simply: Do not add additional functionality to an


existing interface by adding new methods.

Instead, create a new interface and let your class implement


multiple interfaces if needed.
Deals with non-cohesive interfaces!
Coupling
• This principle deals with the disadvantages of “fat”
interfaces.
• Classes that have “fat” interfaces are classes whose
interfaces are not cohesive.

• The interfaces of the class can be broken up into groups


of member functions.
• Each group serves a different set of clients.
• Thus some clients use one group of member functions, and
other clients use the other groups.
•Fat interfaces lead to inadvertent
couplings between clients that ought
otherwise to be isolated.
•Fat interfaces can be segregated into
abstract base classes that break the
unwanted coupling between clients.
•The ISP acknowledges that there are objects
that require non-cohesive interfaces

•It suggests that clients should not know


about them as a single class.
•Instead, clients should know about abstract
base classes that have cohesive interfaces.
Software Design and
Architecture

Topic#056
END!
Software Design and
Architecture
Topic#057
SOLID Design Principles
Interface Segregation Principle (ISP) - Example
interface IPost
Initially an IPost interface
{ with the signature of a
void CreatePost(); CreatePost() method.
}

interface IPost
{
void CreatePost(); Later on, a new method
void ReadPost(); ReadPost() added to it
}
Violation of ISP!
Old clients do not need the new interface
To avoid the problem, simply create
a new interface
interface IPostCreate If any class might
{
void CreatePost(); need both the
} CreatePost() method
and the ReadPost()
interface IPostRead method, it will
{
void ReadPost();
implement both
} interfaces.
Complying to ISP!
Software Design and
Architecture

Topic#057
END!
Software Design and
Architecture
Topic#058
SOLID Design Principles
Dependency Inversion Principle (DIP)
The Dependency-Inversion Principle (DIP)
1. High-level modules should not depend on low-level
modules. Both should depend on abstractions.
2. Abstractions should not depend upon details. Details
should depend upon abstractions.
In programming, the dependency inversion
principle is a way to decouple software
modules.
The Dependency-Inversion Principle (DIP)

Natural progression of the Liskov Substitution


Principle, the Open Closed Principle and even
the Single Responsibility Principle.
The Dependency-Inversion Principle (DIP)
• The problem of dependency is most often
solved by using dependency injection.
• Typically, dependency injection is used
simply by ‘injecting’ any dependencies of a
class through the class’ constructor as an
input parameter.
• Using association
Software Design and
Architecture

Topic#058
END!
Software Design and
Architecture
Topic#059
SOLID Design Principles
Dependency Inversion Principle (DIP) - Example
class Post
{
private ErrorLogger errorLogger = new ErrorLogger(); Dependency
void CreatePost(Database db, string postMessage)
{
We create the ErrorLogger instance
try
{ from within the Post class.
db.Add(postMessage);
} This is a violation of the dependency
catch (Exception ex) inversion principle.
{
errorLogger.log(ex.ToString())
}
If we wanted to use a different kind }
of logger, we would have to modify
} the Post class.
class Post
{
private Logger _logger;

public Post(Logger injectedLogger)


{
_logger = injectedLogger; Dependency Injection
}

void CreatePost(Database db, string postMessage)


{
// no change here
}
}
Software Design and
Architecture

Topic#059
END!
Software Design and
Architecture
Topic#060
Good OO design principles
Law of Demeter (LoD)
Law of Demeter – A Style Rule for building systems
• Demeter Origins
• Proposed by The Demeter Research Group in 1987
• "Law of Demeter" Paper
• Lieberherr, Karl. J. and Holland, I., “Assuring good
style for object-oriented programs”, IEEE Software,
September 1989, pp 38-48
• Covered in many major books on OO design and
programming.
Reduces coupling and improves maintainability
Law of Demeter – A Style Rule for building systems
• Its essence is the "principle of least knowledge"
regarding the object instances used within a
method.
Law of Demeter – A Style Rule for building systems
The Law of Demeter says that if I need to request
a service of an objects sub-part, I should instead
make the request of the object itself and let it
propagate this request to all relevant sub-parts,
thus the object is responsible for knowing its
internal make-up instead of the method that uses
it.
Law of Demeter in its original form
• For all classes C, and for all methods M attached to
C, all objects to which M sends a message must be:

• M’s argument objects, including the self object or


• The instance variable objects of C
• Object created by M, or by functions or methods
which M calls, and objects in global variables are
considered as arguments of M.
Law of Demeter Principle
• Each unit should only use a limited set of other
units: only units “closely” related to the current
unit.

• “Each unit should only talk to its friends.”


• “Don’t talk to strangers.”
A side-effect of this is that if you
conform to LoD, while it may quite
increase the maintainability and
"adaptiveness" of your software system,
you also end up having to write lots of
little wrapper methods to propagate
methods calls to its components
Software Design and
Architecture

Topic#060
END!
Software Design and
Architecture
Topic#061
Good OO design principles
Law of Demeter (LoD) - Example
Register needs to find out the amount of the payment

Register Sale Payment


paymentAmount() becomeComplete()
endSale() makeLineItem() getTenderedAmount()
enterItem() makePayment()
makePayment() getTotal()
... ...
The class diagram shows that
•Register knows about Sale, and
•Sale knows about the corresponding Payments
public void paymentAmount()
{
Payment payment = sale.getPayment();
Money amount = payment.getTenderedAmount();

// same as:
// Money amount = sale.getPayment().getTenderedAmount();
// chain calls

}
getTenderedAmount() getPayment()
:Payment :Register :Sale
Register Sale Payment

Model vs Actual
getTenderedAmount() getPayment()
:Payment :Register :Sale
Payment is stranger to Register
(not visible in the model)
hidden dependency – not visible in the model but present in the code

Register Sale Payment

paymentAmount() becomeComplete() getTenderedAmount()


endSale() makeLineItem()
enterItem() makePayment()
makePayment() getTotal()
... ...
Register has a “hidden” dependency on Payment
This increases the coupling in our system
LoD – Don’t Talk to Strangers

Register Sale Payment

paymentAmount() becomeComplete()
makeLineItem() getTenderedAmount()
endSale()
enterItem() makePayment()
makePayment() getTotal()
... getPayment
...
add a method to
get a payment
LoD – Don’t Talk to Strangers
If getPayment() in Sale would invoke getTenderedAmount() in Payment, and
return the payment amount, then we can de-couple Register from Payment

Register will get the payment


amount it is after, but it won’t know
how it was obtained - see Parnas’
Objects are only sending concept of information hiding on
messages to their friends
make the solution more robust, less sensitive to changes, less coupling
Software Design and Architecture

Topic#061

END
Software Design and Architecture

Fakhar Lodhi
Object-Oriented Design
Solutions to some general design problems
Software Design and
Architecture
Topic#062
Action-Oriented Design in the Disguise of object-
Oriented Design
Good OOD practices

• High cohesion and low coupling


• An object must be able to answer the following:
• who I am?
• who I know?
• what I know? • Principle of delegation
• what I do?
identity

data

methods

relationships
Design Challenges with OO Paradigm
• Poorly distributed system intelligence
• god classes
• Behavioral form - can’t answer what I know
• Data form - can’t answer what I do
god class problem – behavioral
form
• Action-oriented in the disguise of object-oriented
• Central control mechanism
• Super object that does most of the work leaving
minor details to a collection of trivial classes
Distribute system intelligence horizontally as
uniformly as possible
Topic#062
END!
Topic#063
Handling Poorly Distributed System Intelligence
Desired
Temp

actualTemp()
Actual Heat Flow
Temp Regulator Furnace

Occupancy
Room
Desired
Temp desiredTemp()
actualTemp() Heat Flow
Actual Furnace
Temp anyonePresent() Regulator

Occupancy
Room

Desired
Temp
doYouNeedHeat()
Actual Heat Flow
Furnace
Temp Regulator

Occupancy
Topic#063

END!
Topic#064

Modelling Policy – Jacobson’s Heuristic


 Student – Course – Course Offering

 Courseoffering would like to check that the


student has taken the pre-reqs.

 How to perform this function?


– Student knows which course he/she has taken
– Course knows the pre-reqs

Policy Information
Requires data of two classes to make a decision.
Course Student Course Student
check() getCourses() getPrereqs() check()

PreRequisites Courses PreRequisites Courses

addStudent() addStudent()

CourseOffering CourseOffering
Jocobson’s Heuristic
Policy information should not be
placed inside of classes involved in
the policy decision because it
renders them un-reusable by binding
them to the domain that sets the
policy.
Controller Class
Course Student
getPrereqs() getCourses()
PreRequisites Courses

What I know?
check()
PrereqCh ecker

addStudent()

CourseOffering
Topic#064

END!
Topic#065
Handling roles - Player-Role Pattern
Roles

Student Teacher Parent


Name, Contact Name, Contact Name, Contact
Registration No. Employee ID Something
Roles
Person
Name, Contact

Student Teacher Parent


Registration No. Employee ID Something
If one person plays different roles
Data Coherence Problem
Role Object
Person 1
* Person Role
Name, Contact

Student Teacher Parent

Employee ID
Registration No. something
Topic#065

END!
Topic#066
Handling multiple discriminators using Player-
Role Pattern
• A discriminator is a label that
describes the criteria used in the
specialization

• Can be thought of an attribute that


will have a different value in each
subclass
Handling multiple discriminators by
Creating higher-level generalization
Animal

habitat

AquaticAnimal LandAnimal

ty peOf Food ty peOf Food


AquaticCarnivore AquaticHerbivore
Properties associated with both
discriminators have to be present
All the features associated with the second
generalization set would have to be duplicated
No. of classes can grow very large
Try adding omnivores and/or amphibians!
Handling multiple discriminators by
Using Multiple Inheritance
Animal

habitat typeOfFood

AquaticAnimal LandAnimal Carnivore Herbivore


AquaticCarnivore AquaticHerbivore LandCarnivore LandHerbivore
Animal

habitat
typeOfFood

AquaticAnimal LandAnimal
Carnivore Herbivore

AquaticCarnivore AquaticHerbivore LandCarnivore LandHerbivore

Avoids duplication of features


Animal
habitat
typeOfFood

AquaticAnimal LandAnimal
Carnivore Herbivore

AquaticCarnivore AquaticHerbivore LandCarnivore LandHerbivore

Adds too much complexity - Proliferation of classes


Not supported by many languages like Java and C#
Handling multiple discriminators by
Using Player-Role Pattern

Animal HabitatRole

typeOfFood habitat

Carnivore Herbivore Omnivore AquaticAnimal LandAnimal


Can very easily add Amphibian
Topic#066

END!
Topic#067
Abstraction-Occurrence Pattern
LibraryItem
name
author
isbn
publicationDate
libOfCongress
barCodeNumber
Title
name
author
isbn
publicationDate
libOfCongress
IsA
LibraryItem Relationship?
barCodeNumber
Title LibraryItem
*
name AccNo
author
isbn
publicationDate
libOfCongress
The 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
Abstraction-Occurrence - Examples

TVSeries Episode
seriesName number
producer title
storySynopsis
Square variant
ScheduledTrain SpecificTrain
*
number date

ScheduledLeg *
SpecificLeg
scheduledDepTime actualDepTime
scheduledArrTime actualArrTime

origin destination
Station
Topic#067
END!
Topic#068
Reflexive Associations
An association to connect a class to itself
successor

isMutuallyExclusiveWith
Course

*
prerequisite
Two main types: Symmetric and Asymmetric.
• The ends of the association are semantically different from
each other, even though the associated class is the same.

• Examples:
• parent-child, supervisor-subordinate, and predecessor-
successor, course-prerequisite
// Example - asymmetric association

class Person {
Person *parents[2];

};
// Example - asymmetric association with role name
// on the other end

class Person {
Person *parents[2];
vector <Person *> child;

}
Symmetric Reflexive Association
• There is no logical difference in the semantics of each
association end
• Example:
• mutually exclusive courses
• students who have taken one course cannot take
another in the set
• If course A is mutually exclusive with B, then course
B is mutually exclusive with A
Symmetric Reflexive Association

// Example symmetric association.

class Course {
Course *mutuallyExclusiveWith[3];
};
Software Design and
Architecture

Topic#068
END!
Software Design and Architecture

Fakhar Lodhi
Topics Covered: 069 – 075
Design Patterns
Software Design and
Architecture

Topic#069
Design Patterns –
Introduction
•Good OOD is more than just knowing
and applying concepts like abstraction,
inheritance, and polymorphism
•A design guru thinks about how to create
flexible designs that are maintainable
and that can cope with change.
Design Patterns
“Each pattern describes a problem which occurs
over and over again in our environment and then
describes the core of the solution to that problem, in
such a way that you can use this solution a million
times over, without ever doing it in the same way
twice”

•Christopher Alexander, A Pattern Language, 1977


•Context: City Planning and Building architectures
Software Design Patterns
•Search for recurring successful designs – emergent
designs from practice
•Described in Gama, Helm, Johnson, Vlissides
1995 (i.e., “gang of 4 book” aka GoF)
•Represent solutions to problems that arise when
developing software within a particular context.
•Describes recurring design structures
•Describes the context of usage
What Makes it a Pattern?
•A Pattern must:
•Solve a problem and be useful
•Have a context and can describe where the solution can
be used
•Recur in relevant situations
•Provide sufficient understanding to tailor the solution
•Have a name and be referenced consistently
•Patterns capture the static and dynamic
structure and collaboration among key
participants in software designs

•Especially good for describing how and why to


resolve non-functional issues
•Patterns facilitate reuse of successful software
architectures and designs.
Software Design and

Architecture

Topic#069 END!
Software Design and
Architecture

Topic#070
Elements of design patterns
Elements of Design Patterns
•Design patterns have four essential elements:
•Pattern name
•Problem
•Solution
•Consequences
Pattern Name
•A handle used to describe:
• a design problem
• its solutions
• its consequences
•Increases design vocabulary
•Makes it possible to design at a higher level of abstraction
•Enhances communication
•“The Hardest part of programming is coming up with good
variable [function, and type] names.”
<<

Creator1
FactoryMethod()

Product
Factory
Creator <<interface>>

FactoryMethod()

Operation()
Product

Method

Product =
factoryMethod();

Product1

Create>>
Problem
•Describes when to apply the pattern
•Explains the problem and its context
•May describe specific design problems and/or
object structures
•May contain a list of preconditions that must be
met before it makes sense to apply the pattern
Solution
•Describes the elements that make up the
•design
•relationships
•responsibilities
•collaborations
•Abstract description of design problems and how the
pattern solves it
•Does not describe specific concrete implementation

Consequences
•Results and trade-offs of applying the pattern
•Critical for:
•evaluating design alternatives
•understanding costs
•understanding benefits of applying the pattern
•Includes the impacts of a pattern on a system’s:
•flexibility
•extensibility
•portability
Design Pattern Descriptions
• Name and Classification: Essence of pattern
• Intent: What it does, its rationale, its context
• AKA: Other well-known names
• Motivation: Scenario illustrates a design problem
• Applicability: Situations where pattern can be applied
• Structure: Class and interaction diagrams
• Participants: Objects/classes and their responsibilities
• Collaborations: How participants collaborate
• Consequences: Trade-offs and results
• Implementation: Pitfalls, hints, techniques, etc.
• Sample Code
• Known Uses: Examples of pattern in real systems
• Related Patterns: Closely related patterns
Software Design and

Architecture

Topic#070 END!
Software Design and
Architecture

Topic#071
Categories of Design Patterns
Categories of Patterns
•Creational patterns (5)
• Deal with initializing and configuring classes and objects
•Structural patterns (8)
• Deal with decoupling interface and implementation of classes
and objects
• Composition of classes or objects
•Behavioural patterns (11)
• Deal with dynamic interactions among societies of classes and
objects
• How they distribute responsibility

Pattern Types
•Class Patterns (4)
•Deal with relationships between classes and their
subclasses
•Established through inheritance, so they are staticfixed
at compile-time
•Object Patterns (20)
•Deal with object relationships
•Established through association
•Can be changed at run-time and are more dynamic
Purpose
Creational Structural Behavioural
Scope Class • Factory • Adapter • Interpreter
method (class) • Template method
Object • Abstract • Adapter • Chain of responsibility
factory (object) • Command
• Builder • Bridge • Iterator
• Prototype • Composite • Mediator
• Singleton • Decorator • Memento
• Façade • Observer
• Flyweight • State
• Proxy • Strategy
Software Design and

Architecture

Topic#071 END!
Software Design and
Architecture
Topic#072
Benefits and drawbacks of design patterns
Benefits of Design Patterns
•Design patterns enable large-scale reuse of software
architectures and also help document systems
•Patterns explicitly capture expert knowledge and
design trade-offs and make it more widely available
•Pattern names form a common vocabulary
•Patterns help improve developer communication
•Patterns help ease the transition to OO technology

Drawbacks to Design
Patterns
•Patterns do not lead to direct code reuse
•Patterns are deceptively simple
•Patterns are validated by experience and discussion
rather than by automated testing
•Integrating patterns into a software development
process is a human-intensive activity.

Design Patterns are NOT


•Designs that can be encoded in classes and reused as
is (i.e., linked lists, hash tables)
• Complex domain-specific designs (for an entire
application or subsystem)

•They are:
•“Descriptions of communicating objects and classes
that are customized to solve a general design problem
in a particular context.”
Software Design and

Architecture

Topic#072 END!
Software Design and
Architecture

Topic#073
Singleton Design Pattern
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

Singleton - Uses
Use the Singleton when:
•There must be exactly one (or fixed number) instance of
the class and it must be accessible to clients from a
wellknown access point

Singleton - Structure
Singleton
static Instance()
SingletonOperation()
GetSingletonData()

static uniqueInstance
singletonData
Implementation
Class Singleton { Singleton* Singleton::
public: _instance= NULL;
static singleton* Instance();
Singleton* Singleton::Instance() {
protected:
if (_instance == NULL) {
Singleton(); _instance = new Singleton;
private: }
static singleton* _instance; return _instance;
}; }
Software Design and

Architecture

Topic#073 END!
Software Design and
Architecture

Topic#074
Strategy Design Pattern
SimDuck
Add fly()
•What about a rubber duck?
Rubber Duck
Violation of LSP
Another duck
Violation
of LSP
Multiple
Interfaces
Associate Algorithms
public abstract class Duck {
FlyBehavior flyBehavior;
QuackBehavior quackBehavior;
public Duck() { } public
abstract void display(); public
void performFly() {
flyBehavior.fly();
} public void
performQuack() {
quackBehavior.quack();
}
// other
public class MallardDuck extends Duck {
public MallardDuck() { quackBehavior
= new Quack();
flyBehavior = new fly();

// other

}
}
Strategy Pattern
Defines a family of
algorithms, encapsulates
each one, and makes
them interchangeable.
Strategy lets the
algorithm vary
independently from
clients that use it.
Software Design and

Architecture

Topic#074 END!
Software Design and
Architecture
Topic#075 Object-Morphing and Strategy
Pattern
Employee

benefits()

TraineeEmployee RegularEmployee

benefits() benefits()

Everything seems satisfactory until we think


about the life of the traineeEmployee object
Object Morphing
Avoiding having instances change
class
•Object Morphing
•When an instance changes its class
•An instance should never need to change class
•You have to destroy the old one and create a new one.
•What happens to associated objects?
•You have to make sure that all links that connected to
the old object now connect to the new one.

EmployeeBenefits
Employee
benefits()
TraineeEmployeeBenefits RegularEmployeeBenefits

benefits() benefits()

Object Morphing and Strategy Design Pattern


Software Design and
Architecture
Topic#075
END1!
Software Design and Architecture

Fakhar Lodhi
Topics Covered: 076 – 082
Design Patterns – Part II
Software Design and
Architecture

Topic#076
Façade Design Pattern
Problem
•There is a legacy application written in C
•There is a rich library of functionality
that is very difficult to be re-written
•A new GUI-based interface needs to be
added to the application
Problem
The application needs to be
“object-orientized” to make it
communicate/compatible with the
rest of a newly built system.

How to go about it?


Facade Pattern
•Structural Pattern
•Provides a unified interface to a set of interfaces in a
subsystem.
•Defines a higher-level interface that makes the
subsystem easier to use.
•Wraps a complicated subsystem with a simpler interface.
Facade
• The principal front of a building, that
faces on to a street or open space
• A deceptive outward appearance
General-building-façade: From Wikimedia Commons

Facade Pattern
•Involves a single class which provides simplified methods
required by client and delegates calls to methods of
existing system classes.
•Can be used to add an interface to existing system to
hide its complexities.
Facade objects are
often Singletons
because only one
Facade object is
required.
Software Design and

Architecture

Topic#076 END!
Software Design and
Architecture

Topic#077
Modeling Sate Machine
Gumball Machine
By putting CPUs into their machines, they can
increase sales, monitor inventory over the
network and measure customer satisfaction
more accurately.
Gumball Machine – Sate Diagram
Implementing State Machines
Step 1: Identify states

1.SOLD_OUT
2.NO_QUARTERS
3.HAS_QUARTERS
4.SOLD
Implementing State Machines
Step 2: Create instance variables to hold state

final static int SOLD_OUT = 0; final


static int NO_QUARTERS = 1; final static
int HAS_QUARTERS = 2; final static int
SOLD = 3; Implementing State
Machines
Step 3: Identify initial state

int state = SOLD_OUT;


int count = 0;
Implementing State
Machines
The Gumball Machine Class so far
public class GumballMachine {

final static int SOLD_OUT = 0; final static


int NO_QUARTERS = 1; final static int
HAS_QUARTERS = 2; final static int SOLD
= 3;
int state = SOLD_OUT;
int count = 0;
Implementing State Machines
Step 5: List all the actions that happen in the system
1.Inserts quarters
2.Turns crank
3.Dispense
4.Ejects Quarters
Implementing State Machines
Step 6: Create a method that acts as the state
machine
• Gumball machine class
• A method for each action
• We use conditionals to determine what
behavior is appropriate in each state
public void insertQuarter ( ) { if
(state == HAS_QUARTER) {
System.out.println(“ Can’t insert another quarter”);
} else if (state == SOLD_OUT) {
System.out.println(
“ Can’t insert a quarter, the machine is sold out”); } else
if (state == SOLD) {
System.out.println (
“ Please wait we are getting you a gumball”);
} else if (state == NO_QUARTER) {
state = HAS_QUARTER;
System.out.println(“You inserted a quarter”);
}
}
public void ejectQuarter ( ) { … }
public void turnCrank ( ) { … }
public void dispense ( ) { … }
public void somthingElse ( ) { … }
Everything seems satisfactory until we need
some changes
New Requirements

•Turn gumball buying into a game!


•10% of the time when the crank is
turned, the customer gets two
gumballs instead on one!
New State Diagram
•add a new state
•add three new methods
•add a new condition in each of the existing methods that
correspond to action.
Solution: State Pattern
Software Design and

Architecture

Topic#077 END!
Software Design and
Architecture

Topic#078
State Design Pattern
The State Pattern
The State Pattern allows an object
to alter its behavior when its
internal state changes. The object
will appear to change its class.
State Design Pattern:
Motivation
•The State pattern is useful when you want to have
an object represent the state of an application,
and you want to change the state by changing
that object.
•The State pattern is intended to provide a
mechanism to allow an object to alter its
behavior in response to internal state changes.
State Design Pattern:
Motivation
•To the client, it appears as though the object has
changed its class.
•The benefit of the State pattern is that statespecific
logic is localized in classes that represent that state.
Context State

request () handle()

state.handle()
ConcreteStateA ConcreteStateB

handle() handle()
State Design Pattern Structure
Context State

request() handle()

state .handle()
ConcreteStateA ConcreteStateB

handle() handle()
The context is the class that can have a number
of internal states – for example Gumball Machine
Context State

request() handle()

state .handle()
ConcreteStateA ConcreteStateB

handle() handle()
defines the interface of interest to clients

Context State

request() handle()

state .handle()
ConcreteStateA ConcreteStateB

handle() handle()
maintains an instance of a ConcreteState
subclass that defines the current state
request () handle()

state.handle()
ConcreteStateA ConcreteStateB

handle() handle()
Whenever the request() is made on the Context,
it is delegated to the State handle()
Context State

request () handle()

state.handle()
ConcreteStateA ConcreteStateB

handle() handle()
defines an interface for encapsulating the
behavior associated with a particular state of the
Context
Context State

request () handle()

state.handle()
ConcreteStateA ConcreteStateB

handle() handle()

Each state is represented by a concrete state


class – There are many concrete state classes
Context State

request () handle()

state.handle()
ConcreteStateA ConcreteStateB

handle() handle()

Concrete states handle request from the Context


Context State

request () handle()

state.handle()
ConcreteStateA ConcreteStateB

handle() handle()

Each Concrete state provides its own


implementation for a request – in this way the
context changes state
Software Design and

Architecture

Topic#078 END!
Software Design and
Architecture

Topic#079
State Design Pattern - Example
Gumball Machine - The new
design
1. Define a State interface that contains a method for
every action in the Gumball Machine
2. Implement a State class for every state of the machine.
These classes will be responsible for the behavior of
the machine when it is in the corresponding state
• We are going to get rid of all the conditional code and
instead delegate to the state class to do all the work
State

insertQuarter ()
ejectQuarter ()
turnCrank ()
dispense ()

SoldState SoldOutState NoQuarterState HasQuarterState

insertQuarter () insertQuarter () insertQuarter () insertQuarter ()


ejectQuarter () ejectQuarter () ejectQuarter () ejectQuarter ()
turnCrank () turnCrank () turnCrank () turnCrank ()
dispense () dispense () dispense () dispense ()
public class NoQuarterState extends State {
GumballMachine gbMachine;

public NoQuarterState (GumballMachine gbm) {


this.gbMachine = gbm; constructor
}

public void insertQuarter() { Do the


system.out.println(“You have inserted a quarter”);

gbMachine.setState(gbMachine.hasQuarterState.getState(); needful
} and then
public void ejectQuarter() { change
system.out.println(“You have not inserted a quarter”);

} state to

} next
state
public class GumballMachine {
State soldState; All state objects
State soldOutState; are created and
State noQuarterState; assigned in State
hasQuarterState; constructor

State state = soldOutState; object int count = 0;


representing the public void insertQuarter();
current state
public class GumballMachine {
… initialized to
} soldOutState

public void insertQuarter() { Just delegate.
state.insertQuarter();
} That’s it!!

}
public class GumballMachine {
•Localized the behavior of each state into its own class
•Removed all if statements

public void insertQuarter() { Just delegate.
state.insertQuarter();
} That’s it!!

}
public class GumballMachine {
•When an action is called, it is delegated to the current
state
•It does the needful and sets the state to the next state
State Pattern - Summary
•Allows a context to change its behavior as the state of
the context changes
•When an action is called, it is delegated to the current
state
•It does the needful and sets the state to the next state
•By encapsulating each state in a class, we localize any
changes that need to be made.
Software Design and

Architecture

Topic#079 END!
Software Design and
Architecture
Topic#080
Comparison of Strategy and State Design Patterns
Everything seems satisfactory until we think
about the life of the traineeEmployee object
Object Morphing
Strategy vs State
State vs Strategy
•They are both examples of association with
delegation
•The difference between the State and
Strategy patterns is one of intent
State Strategy
• Set of behaviors encapsulated in • Client usually specifies the strategy
state objects; object that the context is associated
• At any time the context is with.
delegating to one of those states. • While the pattern provides the flexibility
• Over time, the current state to change the strategy object at run
changes across the set of state time, there is one strategy object that is
objects to reflect the internal most appropriate for a context object.
state of the context, so the • Flexible alternative to subclassing: if you
context’s behavior changes over use inheritance to define the behavior of
time. Client knows very little, if a class, you are stuck with it even if you
anything, about the state objects need to change it.
• Alternative to putting a lots of • With strategy you can change the
conditional in the context behavior by associating it with different
objects
Software Design and

Architecture

Topic#080 END!
Software Design and
Architecture

Topic#081
Composite Design Pattern
Employee

Secretary Technician Manager


A company has different types of employees

Problem: a manager manages other employees


How to model?

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).
• Some objects cannot have any subordinates • Problem:
• How can we represent a hierarchy of objects, in which some objects cannot
have subordinates?
•Forces:
• You want a flexible way of representing the hierarchy
• that prevents certain objects from having subordinates
• All the objects have many common properties and operations
The General Hierarchy Pattern
aka Composite Pattern
«Node» *
«subordinate»

0..1
«NonSuperiorNode» «SuperiorNode»
Employee * supervises FileSystemItem * contains

0..1 0..1
Secretary Technician Manager File Directory
The General Hierarchy
Pattern aka Composite
Pattern
*
«Node»
«subordinate»

0..1

«NonSuperiorNode» «SuperiorNode»
The General Hierarchy
Pattern
Employee * supervises

0..1

Secretary Technician Manager


The Composite Pattern
FileSystemItem * contains

0..1

File Directory
•The difference between a tree data
structure and the composite pattern

•In the case of a tree data structure,


all nodes have the same structure
and behavior
Software Design and

Architecture

Topic#081 END!
Software Design and
Architecture

Topic#082
Observer Design Pattern
Excel - Example
Observer Pattern
•Defines a “one-to-many” dependency
between objects so that when one object
changes state, all its dependents are notified
and updated automatically
•a.k.a Dependence mechanism /
publishsubscribe / broadcast / change-
update
Subject & Observer
•Subject
•the object which will frequently change its
state and upon which other objects depend

•Observer
•the object which depends on a subject and
updates according to its subject's state.
Observer Pattern - Example
Observer Pattern - UML
Observer Pattern - UML
observers
Subject
Attach(Observer)
Detach(Observer)
Notify() for all o in
observers {
o -> Update()}

subject
ConcreteSubject

SetState() return subjectState


GetState()
observerState =
subject->GetState()

subjectState
Observer Pattern - UML
observers
Subject Observer
Attach(Observer) Update()
Detach(Observer)
Notify() for all o in
observers {
o -> Update()}

ConcreteObserver
observerState =
Update() subject->GetState()
subject
ConcreteSubject observerState
SetState() return subjectState
GetState()

subjectState Subject has a list of observers


Interfaces for attaching/detaching an observer
Observer Pattern - UML
observers
Subject Observer
Attach(Observer) Update()
Detach(Observer)
Notify() for all o in
observers {
o -> Update()}

ConcreteObserver
observerState =
Update() subject->GetState()
subject
ConcreteSubject observerState
SetState() return subjectState
GetState()

subjectState
Observer has an updating interface for objects
that gets notified of changes in a subject
Observer Pattern - UML
observers
Subject Observer
Attach(Observer) Update()
Detach(Observer)
Notify() for all o in
observers {
o -> Update()}

ConcreteObserver
observerState =
Update() subject->GetState()
subject
ConcreteSubject observerState
SetState() return subjectState
GetState()

subjectState Concrete Subject Stores “state of interest” to


observers and Sends notification when state
changes
Observer Pattern - UML
observers
Subject Observer
Attach(Observer) Update()
Detach(Observer)
Notify() for all o in
observers {
o -> Update()}

ConcreteObserver
observerState =
Update() subject->GetState()
subject
ConcreteSubject observerState
SetState() return subjectState
GetState()

Concrete Observer Implements updating


subjectState
interface
Observer Pattern - UML
observers
Subject Observer
Attach(Observer) Update()
Detach(Observer)
Notify() for all o in
observers {
o -> Update()}

ConcreteObserver
observerState =
Update() subject->GetState()
subject
ConcreteSubject observerState
SetState() return subjectState
GetState()
subjectState
A number of Observers “register” to receive
notifications of changes to the Subject.
Observer Pattern - UML
observers
Subject Observer
Attach(Observer) Update()
Detach(Observer)
Notify() for all o in
observers {
o -> Update()}

ConcreteObserver
observerState =
Update() subject->GetState()
subject
ConcreteSubject observerState
SetState() return subjectState
GetState()
subjectState
A number of Observers “register” to receive
notifications of changes to the Subject.
Observer Pattern - UML
observers
Subject Observer
Attach(Observer) Update()
Detach(Observer)
Notify() for all o in
observers {
o -> Update()}

ConcreteObserver
observerState =
Update() subject->GetState()
subject
ConcreteSubject observerState
SetState() return subjectState
GetState()
subjectState
When a certain event or “change” in Subject
occurs, all Observers are “notified’.
Observer Pattern - Consequences
• Loosely Coupled
• Reuse subjects without reusing their observers, and vice versa
• Add observers without modifying the subject or other observers

• Abstract coupling between subject and observer


• Concrete class of none of the observers is known

• Support for broadcast communication


subjectState
• Subject doesn’t need to know its receivers

subjectState
Software Design and

Architecture

Topic#082 END!
subjectState
subjectState

You might also like