cs603 Handouts 001-082
cs603 Handouts 001-082
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
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
+
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
An Art
Software Design and
Architecture
Topic#007 END!
Software Design and
Architecture
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
•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
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
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
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 onclick="highlight2()">Highlight </button>
<button onclick="normal2()">Normal </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 onclick="highlight2()">Highlight </button>
<button onclick="normal2()">Normal </button>
<h1 id="title" class="NormalClass">
CSS <--> JavaScript Coupling
</h1>
We want to change the
</body>
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
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
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
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
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
•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
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
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
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..*
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.
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();
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
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;
}
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.
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.
Fakhar->addcourse(SE101);
}
void course::addlecturer(lecturer *teacher)
{
L = teacher;
L -> addcourse(this);
}
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
Topic#048
END!
Software Design and
Architecture
Topic#049
SOLID Design Principles
Single Responsibility Principle (SRP)
Single Responsibility Principle (SRP)
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);
}
}
{
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:
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
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.
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.
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.
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.
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)
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;
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:
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
// 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
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
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
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
Policy Information
Requires data of two classes to make a decision.
Course Student Course Student
check() getCourses() getPrereqs() check()
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
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
habitat
AquaticAnimal LandAnimal
habitat typeOfFood
habitat
typeOfFood
AquaticAnimal LandAnimal
Carnivore Herbivore
AquaticAnimal LandAnimal
Carnivore Herbivore
Animal HabitatRole
typeOfFood habitat
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
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”
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.
•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()
EmployeeBenefits
Employee
benefits()
TraineeEmployeeBenefits RegularEmployeeBenefits
benefits() benefits()
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.
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
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()
request () handle()
state.handle()
ConcreteStateA ConcreteStateB
handle() handle()
request () handle()
state.handle()
ConcreteStateA ConcreteStateB
handle() handle()
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 ()
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
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
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
0..1
File Directory
•The difference between a tree data
structure and the composite pattern
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
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()
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()
ConcreteObserver
observerState =
Update() subject->GetState()
subject
ConcreteSubject observerState
SetState() return subjectState
GetState()
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
subjectState
Software Design and
Architecture
Topic#082 END!
subjectState
subjectState