SlideShare uma empresa Scribd logo
1 de 132
CPIT-252
DESIGN PATTERNS
Teacher: Dr. Asma Cherif
Office room: 144S
email: acherif@kau.edu.sa
IT dept.
Course Coordinator: Dr. Asma Cherif
1
REFERENCES
Many resources have been used to build this course, if you notice any missing reference please
contact me at acherif@kau.edu.sa
• GoF book
• Laurent Audibert (developpez.com)
• Dr. Birgit Demuth (OCL)
• Dr. K.M Anderson
• Head First Collection
• Software engineering, Ian Sommerville, ch2- quality management
• www.newthinktank.com
• https://sourcemaking.com
• Derek Banas youtube channel
2
GENERAL
INTRODUCTION
Course description
Course outline
Course objectives
Mark distribution
References
Course Objectives
1. Generate code from class diagrams and vice versa (i)
2. Identify any GoF creational design patterns for code or scenario or design (k)
3. Design and implement GoF creational design patterns (c)
4. Identify any GoF structural design patterns for code or scenario or design (k)
5. Design and implement GoF structural design patterns (c)
6. Identify any GoF behavioural design patterns for code or scenario or design (k)
7. Design and implement GoF behavioural design patterns (c)
8. Design and Implement an application that simulate a medium size project as part of a group (l)
9. Detect the appropriate design patterns in class diagrams (b)
10. Recognize the design patterns from code (k)
11. Produce a pattern based design that maps the requirements of a given scenario using design patterns
(k)
12. Implement code that maps the requirements of a given scenario or designs (c)
13. Evaluate the quality of software design using ISO25001 standard (m)
Textbooks
• Len Bass, Paul Clements, Rick Kazman, "Software
Architecture in Practice", Addison-Wesley
Professional; 2 edition (2003)
• Erich Gamma, John Vlissides, Ralph Johnson, and
Richard Helm, “Design Patterns: Elements of Reusable
Object-Oriented Software”, (1994)
5
DESIGN
Design - Analysis vs Design
- Structured vs OO Design
- Architectural Design -
Design Patterns
What is a design?
• Formulate the maximum alternative solutions
of the problem and select the best one.
• Design Possibilities :
Algorithmic strategy
Decomposition of a system
Abstract function hierarchy
7
8
Types of design
Logical
Forms and
Reports
Interfaces and
Dialog
Physical
Creating
database, tables
and fields
Developing the
logic of the code
using the
algorithm
Hierarchical or
system structure
design
Why do we need design?
9
Provides an
overall picture of
the system
Allows us to
focus on one
thing at a time
Provides concept
reuse (NOT code
reuse)
Simplify
implementation
Assesses quality
Design &
quality
10
The design must implement all of the explicit (clear)
requirements contained in the analysis model, and
it must accommodate all of the implicit (hidden)
requirements desired by the customer.
The design must be a readable, understandable
guide for developers, code generators and testers.
The design should provide a complete picture of the
software.
Design
techniques
Structured
Design
Structure
charts
ERD…
OO design
Use cases
diagram
Interaction
diagram
Class
diagram …
11
Structured Vs OO design
12
Structured Design Object Oriented Design
Basic components functions/procedures classes which include state (behaviors) and functions
Component
relationships
one function calls other functions. One class uses other classes to help it fulfill its
responsibilities (by its methods calling methods in the other
classes)
Inheritance
Classes grouped into packages/subsystems
Design Strategy  Top level function corresponds to program
requirements
 Define this in terms of less abstract functions
 Continue on down until all functions are
concrete
 Refactoring: go back and re-design higher level
functions if design becomes ugly
Identify basic objects/concepts in application domain, and
use these as foundation classes
Select a design architecture
Add additional classes for desired functionality
Abstract out super classes to facilitate understanding and
possible reuse
Refactor as necessary
Analysis and Design
(What and How)
• The analysis model analyses
the problem in the problem
domain, while the design
model analyses the solution
in the solution domain.
Example (structured Design)
14
Analysis
DFD
Design (main
program/subprogram
architectural pattern)
Example (OO design)
15
What is a pattern?
• A pattern is a model or design used as a guide
in needlework and other crafts
• Synonymous:
• Sample, specimen, swatch
16
What is a
pattern?
17
Pattern is a structure or template that is designed
to provide solution of a specific problem.
“A 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 the same way twice.”- Christopher Alexander
A pattern is a recurring solution to a standard
problem, in a context.
Pattern-based Design
• A software designer begins with a
requirements model that presents an abstract
representation of the system.
• The requirements model describes the
problem set, establishes the context, and
identifies the system of forces.
18
Pattern-based design tasks
1. Examine the requirements model and develop a problem hierarchy.
2. Determine if a reliable pattern language has been developed for the problem
domain.
3. Beginning with a broad problem, determine whether one or more architectural
patterns are available for it.
4. Using the collaborations provided for the architectural pattern, examine
subsystem or component level problems and search for appropriate patterns to
address them.
5. Repeat steps 2 through 5 until all broad problems have been addressed.
19
Effective design pattern
A Design Pattern is effective when:
20
It solves a
problem
It is a proven
concept
The solution
isn't obvious
It describes a
relationship
Minimizes
human
intervention
Types of
patterns
Architectural Design Idiom
21
Architectural Design
22
Is an early stage of the system design process.
It represents the link between specification and design processes.
It is often carried out in parallel with some specification activities.
Main objective: identifying the sub-systems making up a system and the framework for sub-system
control and communication.
Output: description of the software architecture.
Architectural
patterns
Distributed Layered Event-driven
Repository-centric Peer to peer
Client Server (
maybe single , two
, or three tiers)
MVC (Model –
View Controller)
MVC (Model – View -
Controller)
• MVC is an architectural
pattern used in software
engineering that separates
the application logic from
business logic.
• Used in web based
applications mainly
How MVC works?
• The user interacts with the UI
• (e.g., user presses a button)
• A controller handles the input event from
the user interface.
• The controller accesses the model, possibly
updating it in a way appropriate to the
user's action.
• The view uses the model to generate an
appropriate user interface
• (e.g., view produces a screen listing
the shopping cart contents).
• The view gets its own data from the model.
The model has no direct knowledge of the
view.
Common
Design
Mistakes
26
Not enough time has been spent to understand the
underlying problem, its context and forces, and as a
consequence, you select a pattern that looks right, but is
inappropriate for the solution required.
Once the wrong pattern is selected, you refuse to see your
error and force fit the pattern.
In other cases, the problem has forces that are not
considered by the pattern you’ve chosen, resulting in a poor
or wrong fit.
Sometimes a pattern is applied too exactly and the required
adaptations for your problem space are not implemented.
Design Patterns and OOP: why do we need
patterns?
• OO approach divides the application to smaller, simpler and reusable
entities.
• However, OO approach can complexify the application if the way you
divide your code does not follow any rule.
• Spagetti effect
• Ex: an application with 40000 lines of code, no architecture  the application
can turn to be difficult to manage which leads to the emergence of bugs that
are difficult to correct (dominos effect)
• To avoid the problem another level of OO design should be followed
• Design patterns
27
What is a design pattern?
• Design pattern is a widely accepted solution to a recurring design problem
in OOP
• A design pattern describes how to structure classes to meet a given
requirement
• Provides a general blueprint to follow when implementing part of a
program
• Does not describe how to structure the entire application
• Does not describe specific algorithms
• Focuses on relationships between classes
• Made popular by Erich Gamma, Richard Helm, Ralph Johnson, and John
Vlissides (authors of design patterns: elements of reusable object-oriented
software)
28
29
Benefits of design patterns
Learn from
community
wisdom
Determine
implementation
faster
Make code
more readable
to other
programmers
Give design
structures
explicit names
Facilitate
refactoring
Types of design patterns
Creational Patterns provide a way to create objects while hiding the creation logic, rather than
instantiating objects directly using new operator. This gives program more
flexibility in deciding which objects need to be created for a given use case.
Structural Patterns concern class and object composition. Concept of inheritance is used to
compose interfaces and define ways to compose objects to obtain new
functionalities.
Behavioral Patterns These design patterns are specifically concerned with communication
between objects.
30
OO DESIGN REVIEW
Pillars of OOP- Class diagram – Interface - relationships between classes
OO Design review
32
The main concept in OOP is the
class.
A class groups data (attributes)
and treatments (methods).
A class is an abstraction describing
how objects act.
An object is an instance of a class.
• It is created in the run time with the new
operator.
Elements in OOP have a scope and
a visibility.
The visibility can be
private/public/protected/package
The 4 pillars of OOP
Abstraction Encapsulation
Polymorphism Inheritance
OOP
33
Class Diagram
• The most important diagram in OOD (obligatory).
• Use case Vs class:
• Use cases diagram illustrates the system according to actors point of view while
• The class diagram illustrates the internal structure of the system. It gives an abtract
representation of system objects that will intercat to accomplish uses cases.
• Gives a static view of the system.
• Main elements:
• Classes
• The relation between classes
• association
• generalization
• dependency
• realization
34
35
Class
Instance variable
methodsfields
Class variable Other functionsconstructor Setter/getter
Non static static
private public
Parameter passing:
1. primitive type: by value
2. reference type: also by value (java)
Fields
36
static(class
variable)
Derived
Methods
• Overloading (be careful the difference is not in the return type only)
• Class method : static method
• Cannot use instance variables (non static fields)
• Cannot call non static methods
• Abstract method: is not implemented
• A class that has at least one abstract
method should be declared abstract
37
abstract
abstract
*A subclass of an abstract superclass should be declared abstract if it does not implement the
abstract inherited methods
Active class
38
Relationship between classes
39
Article
Order
Association
Article
Order
Directed
Association
Employee
0..*
0..1
supervisor
subordinate
Reflexive Association
Multiplicity Role Student Course
Enrollment
date
enroll
drop()
cancel()
0..* 1..*
Association class
Library
Book
Aggregation
Book
Page
Composition
Account
CheckingAccount
Inheritance
Printer
PrinterSetup
Realization
PrinterSetup
Realization
Printer
Order PaymentSystem
Dependency
Multiplicities
40
41
Article
Order
Association
You can give a name and a
direction to the association
42
Article
Order
Association
43
Article
Order
Association
44
Student Course
Enrollment
date
enroll
drop()
cancel()
0..* 1..*
Association class
• A class can have a relationship with other classes.
• The main relation is the inheritance (generalization/specialization).
45
Person
Student Professor
superclass
subclasssubclass
generalization
specialization
Account
CheckingAccount
Inheritance
• A subclass inherits the fields and methods of the super class
• A subclass can add its own fields and methods (specialization)
• A subclass can redefine an inherited method (Overriding)
46
Account
CheckingAccount
Inheritance
• Some times you can’t implement all the details in the super class
• A superclass is abstract when it has at least one abstract method
(without implementation)
• The subclass should implement the abstract method (override)
47
Account
CheckingAccount
Inheritance
• An interface in java is a design of a class.
• It has static constants and abstract methods only.
• The interface allows to achieve fully abstraction: no method body.
• Allows multiple inheritance in Java.
• Java Interface also represents IS-A relationship.
• Interface cannot be instantiated like abstract class.
48
Printer
PrinterSetup
Realization
PrinterSetup
Printer
A class implements an interface, if the class is not abstract,
it should override the methods of the interface
49
Printer
PrinterSetup
Realization
PrinterSetup
Printer
• A class implements an interface
• A class extends a superclass
• An interface extends another interface
50
Printer
PrinterSetup
Realization
PrinterSetup
Printer
Printer
PrinterSetup
Realization
PrinterSetup
Printer
Abstract class Interface
1) Abstract class can have abstract and non- abstract
methods.
Interface can have only abstract methods.
2) Abstract class doesn't support multiple inheritance. Interface supports multiple inheritance.
3) Abstract class can have final, non-final, static and
non-static variables.
Interface has only static and final variables.
4) Abstract class can have static methods, main method
and constructor.
Interface can't have static methods, main method or
constructor.
5) Abstract class can provide the implementation of
interface.
Interface can't provide the implementation of abstract
class.
6) The abstract keyword is used to declare abstract class. The interface keyword is used to declare interface.
7) Example:
public class Shape{
public abstract void draw();
}
Example:
public interface Drawable{
void draw();
}
52
• The dependency means that class A uses class B, but that class A does
not contain an instance of class B as part of its own state.
• It also means that if class B’s interface changes it will likely impact
class A and require it to change.
• You would use dependency to indicate that:
• class A receives an instance of class B as a parameter to at least one of its
methods.
• class A creates an instance of class B local to one of its methods.
• You would not, however, use dependency to indicate that class A
declares an instance variable of class B.
53
Order PaymentSystem
Dependency
54
Order PaymentSystem
Dependency
Or???
55
Order PaymentSystem
Dependency
• An aggregation is a special kind of association
• Instance of aggregator (Library) contains a reference to an instance of
aggregated (Book) as part of the aggregator’s state, but the use of the
specific instance of the aggregated is or may be shared among other
aggregators (!= Library).
• A shared association means that the lifetime of the aggregated object
(the instance of Book), is outside the scope of the referencing object.
 when a specific instance of the aggregator goes out of scope
(garbage collected), the instance of the aggregated does not necessarily
go out of scope.
56
Library
Book
Aggregation
57
Library
Book
Aggregation
58
Book
Page
Composition
Aggregation Vs Composition
• Lifetime of the instance
59
Reverse Engineering
• Reverse Engineer existing Applications consists in generating UML
Models from source code (or binary files) to facilitate analysis,
enhancement, or reuse
• Hand-written or legacy source code can be difficult to understand.
• Some projects incorporate binary or byte-code files that also require
analysis.
• The original developer may no longer be available, or may be development
was assigned in pieces and no single individual knows the entire project.
60
OCL
Object Constraint Language
OCL
• Developed at IBM in 1995 originally as a business engineering language
• Adopted as a formal specification language within UML
• Part of the official UML standard (from version 1.1 on)
• Used to complement UML diagrams
• Extends the Unified Modeling Language (UML)
• Formal language for the definition of constraints and queries on UML models
• Add precise semantics to visual (UML-) models
62
63
What is a
constraint?
64
“A constraint is a restriction on one or more values of (part
of) an object-oriented model or system.“
A constraint is formulated on the level of classes, but its semantics is
applied on the level of objects
originally formulated in the syntactic context of a UML model (i.e a set of
UML diagrams)
65
What are the main
types?
66
Three main elements
1.Invariant 1.Precondition 1.Postcondition
1. Invariant
• An invariant is a constraint that should be true for an object during its
complete lifetime.
• Represents rules that should hold for the real-life objects after which the
software objects are modeled.
context Meeting inv: self.end >
self.start
68
Examples
• context Meeting inv: self.end > self.start
• context Meeting inv: end > start
• context Meeting inv startEndConstraint: self.end > self.start
"self" always refers to the object identifier from
which the constraint is evaluated.
Names can be given to the constraint
69
Exercise
Write the OCL statement to specify that the age is greater than 18.
• Context Employee inv : age >18
• Context Employee inv : self.age >18
• Context Employee inv AgeCST: age >18
70
Employee
name: String
age: int
Precondition/Postcondition
71
Constraints that specify the applicability and effect of an
operation without stating an algorithm or implementation
Are attached to an operation in a class diagram
Allow a more complete specification of a system
2. Precondition
• It is a constraint that must be true just prior to the execution of an operation
Example
73
context Meeting::shift(d:Integer) pre: self.isConfirmed = false
context Meeting::shift(d:Integer) pre: d>0
context Meeting::shift(d:Integer) pre: self.isConfirmed =
false and d>0
3. Postcondition
• It is a constraint that must be true just after the execution of an operation
• Postconditions are the way how the actual effect of an operation is described in OCL.
Example
75
context Meeting::confirm() post: self.isConfirmed =
true
Main Keywords
76
Result
• refers to the result of the
operation
• context
Meeting::duration():Integer
post: result = self.end –
self.start
@pre
• is to be evaluated in the
original state -- before
execution of the operation
• is only allowed in
postconditions
• context Meeting ::
shift(d:Integer) post:
start = start@pre +d and
end = end@pre + d
OCL Expressions
77
Boolean expressions
•Standard library of
primitive types and
associated operations
• Basic types: Boolean,
Integer, Real, String
Collection types
•Set
•Ordered Set
•Bag
•Sequence
User defined types (OCLType)
• Class type:
• A class has the following Features:
• Attributes (start)
• Operations (duration())
• Class attributes (Date::today )
• Class operations
• Association ends (navigation expressions)
• Enumeration type (e.g. Gender, Gender::male)
78
79
OCL Key Notations
80
x.y
Obtain the
property y of
object x
A property
can be an
attribute
A property can
be the set of
objects at the
end of an
association
81
c->f
Apply the built in OCL function f to
collection c
Context Meeting inv :
self.participants -> size()>2
82
Navigation Expressions
• Association ends (role names) used to navigate from one object in the model to another
object.
• Navigations are treated as attributes (dot-Notation).
• The type of a navigation expression is either a
• User defined type (association end with multiplicity at most 1)
• Collection (association end with multiplicity > 1)
83
Example
User defined type
context Meeting context Meeting inv:
self.moderator.gender = Gender::female
Collection
context Meeting inv:
self->collect(participants)->size()>=2
self.participants
84
85
And, or, =, <>
Logical and, or, equal and not equal
Context Person inv :
self.participants -> size()>2
86
p implies q
True if either q is true or p is false
Context Person inv :
isDriver = true implies
age>=18
Sample of operations on sets
88
Exercise
• Specify the requirements:
• A vehicle owner age must be >=18 : Context vehicle inv: owner.age > = 18
• A car owner age must be >=18 :Context car inv: owner.age > = 18
• Nobody has more than 3 vehicles: Context Person inv: (fleet->size())<=3
• Calling birthday() increments the age of a person by 1:
Context Person :: Birthday() post: age = age@pre+1
90
DESIGN PATTERNSIntroduction
What is Gang of Four (GOF)?
• In 1994, four authors Erich Gamma, Richard Helm, Ralph Johnson and John Vlissides
published a book titled Design Patterns - Elements of Reusable Object-Oriented
Software which initiated the concept of Design Pattern in Software development.
• These authors are known as Gang of Four (GOF).
• According to GOF design patterns are primarily based on:
• Program to an interface not an implementation
• Favor object composition over inheritance
92
Elements of Design Patterns
Design patterns have 4 essential elements:
• Pattern name: increases vocabulary of designers
• Problem: intent, context, when to apply
• Solution: UML-like structure, abstract code
• Consequences: results and tradeoffs
93
Describing Design Patterns
• Pattern Name and Classification: A descriptive and unique name that helps in identifying and referring to the pattern.
• Intent: A description of the goal behind the pattern and the reason for using it.
• Motivation (Forces): A scenario consisting of a problem and a context in which this pattern can be used.
• Applicability: Situations in which this pattern is usable; the context for the pattern.
• Structure: A graphical representation of the pattern. Class diagrams and Interaction diagrams may be used for this purpose.
• Participants: A listing of the classes and objects used in the pattern and their roles in the design.
• Collaboration: A description of how classes and objects used in the pattern interact with each other.
• Consequences: A description of the results, side effects, and tradeoffs caused by using the pattern.
• Implementation: A description of an implementation of the pattern; the solution part of the pattern.
• Sample Code: An illustration of how the pattern can be used in a programming language.
• Known Uses: Examples of real usages of the pattern.
• Related Patterns: Other patterns that have some relationship with the pattern; discussion of the differences between the pattern
and similar patterns.
94
Design Patterns are
95
Design Patterns are not
Data structures (i.e.,
linked lists, hash tables)
Complex domain-specific
designs (for an entire
application or subsystem)
What are they?
96
“Descriptions of communicating
objects and classes that are
customized to solve a general
design problem in a particular
context.”
Benefits of Design Patterns
• enable large-scale reuse of software architectures
• help to document systems
• explicitly capture expert knowledge and design tradeoffs and make it more widely available
• help improve developers communication
97
Classification of
design patterns
GF DP classification
purpose
creational
How to create objects while hiding the creation logic
Deal with initializing and configuring classes and objects
structural
Define ways to compose objects to obtain new functionalities.
Deal with decoupling interface and implementation of classes and objects
behavioral
Deal with dynamic interactions among societies of classes and objects
How they distribute responsibility
scope
class
Deal with relationships between classes and their subclasses
Relationships established through inheritance, so they are fixed at compile
time (static)
object
Deal with object relationships
Relationships can be changed at runtime (dynamic)
98
11
5
7
4
20
The Catalog of Design Patterns
99
Purpose
Scope
Creational Structural Behavioral
Class Factory Method Adapter(class) Interpreter
Template Method
Object Abstract Factory
Builder
Prototype
Singleton
Adapter (object)
Bridge
Composite
Decorator
Façade
Flyweight
Proxy
Chain of Responsibility
Command
Iterator
Mediator
Observer
State
Strategy
Visitor
Design Pattern Scope
• Class Patterns (4)
• Deal with relationships between classes and their subclasses
• Relationships established through inheritance, so they are fixed at
compile time (static)
• Object patterns (20)
• Deal with object relationships
• Relationships can be changed at runtime (dynamic)
100
General Introduction-Design
Six types of design patterns
1. Creational class patterns defer some part of object creation to subclasses
2. Creational object patterns defer some part of object creation to another object
3. Structural class patterns use inheritance to compose classes
4. Structural object patterns describe ways to assemble objects
5. Behavioral class patterns use inheritance to describe algorithms and flow of control
6. Behavioral object patterns describe how a group of objects cooperate to perform a task that no
single object can carry out alone 101
Design patterns were
introduced to solve
design problems
102
Problem#1: Finding
Appropriate objects
103
104
The hard
part about
OO design is
decomposing
a system into
objects
Many factors are involved: encapsulation, granularity,
dependency, performance, evolution, reusability, etc.
Many objects come from the analysis model. But we often
end up with classes that has no counterpart in the real
world. Strict modeling of the world leads to a design that
reflect today’s need and not necessarily future.
Abstraction is a way to treat objects that do not have a
physical counterpart.
Design patterns help identify less
obvious abstractions and objects that
can capture them.
Problem#2: Determining
Object Granularity
105
106
How do we
decide
what
should be
an object?
In what
granularity?
Objects can vary in size and
numbers.
They can represent everything
(hardware  entire application)
Design Patterns address this issue.
Example: Façade pattern describe
how to present complete
subsystems as objects.
Problem#3: Specifying object
interfaces
107
108
Interface? Interface = set of signatures, operation signature =
Name + return type + parameters
A type is name used to denote a particular interface
Interfaces are fundamental in OO systems
Objects are known only through their interfaces.
An object interface hides its
implementation
Design patterns help defining
interfaces by determining the
type of data that gets sent across
interfaces.
example: Memento pattern shows
objects must define two interfaces: a
restricted one that hold and copy
mementos and another one that only
original object can use to store and
retrieve state.
Design patterns specify
relationships between
interfaces.
Problem#4: Specifying object
implementations
110
111
Implementation?
An object implementation is defined by its class.
Object instantiations, Class hierarchy,
inheritance, what should be the abstract classes
and what should be concrete classes, etc..?
Patterns such as Composite,
Abstract factory, chain of
responsibility address these issues.
Design Principles behind DP
112
1st good design principle:
Program to an interface not
to an implementation
113
114
Implementation? Class inheritance gives the ability to define new objects in terms of an old one.
Get identical interfaces by inheriting from an abstract class.
All classes derived from an abstract class simply override interfaces and
therefore they can all respond to the requests to the abstract class (i.e they are
all subtypes)
Two benefits:
1- clients remain unaware of the specific type of objects they
use.
2- clients remain unaware of the classes that implement these
objects
Consequences
of the 1st
principle
• Don’t declare variables to be
instances of concrete classes
since clients need only know the
abstract classes
• Creational patterns ensure that
your system is written in terms of
interfaces, not implementations.
115
2nd Design principle: Favor
Composition over
Inheritance
116
Pros and Cons of inheritance
117
CLASS INHERITANCE IS EASY TO USE AND
EASY TO MODIFY (OVERRIDE)
CANNOT CHANGE IMPLEMENTATION AT
RUNTIME
(IT IS DEFINED AT COMPILE TIME)
WORSE IT BREAKS ENCAPSULATION
ANY CHANGE TO PARENT
IMPLEMENTATION WILL FORCE
SUBCLASSES TO CHANGE.
 MAKES REUSE OF SUBCLASSES VERY
LIMITED.
Inheritance weaken
encapsulation
118
Any change to superclass will
break code using subclass
Can we solve this?
How?
119
Object
composition
120
Object Composition is defined dynamically at
runtime (unlike inheritance) through acquiring
references to other objects
does not break encapsulation
Any object can be replaced with another (of
same type) at runtime
so much less implementation dependency
Reuse with
composition
121
Consequences
of the 2nd
principle
• Helps keep each class encapsulated
and focused on one task.
• Classes and class hierarchies will
remain small and more manageable.
• A design with composition will have
more objects and system behavior will
depend on their interrelationship
rather than defined in one class.
• Allow to delegate a request
122
What is the
delegation?
123
124
A WAY TO MAKING
COMPOSITION POWERFUL
FOR REUSE.
TWO OBJECTS ARE
INVOLVED IN HANDLING A
REQUEST
ONE OBJECT RECEIVES THE
REQUEST, AND DELEGATES
THE REQUEST TO BE
HANDLED BY ITS DELEGATE.
Example: Window and Rectangle objects
125
instead of using inheritance, by defining window as being a
rectangle, it can have a rectangle as attribute
However!
126
127
Delegation makes easy to compose behaviors at run-time (e.g. window
can become circle instead of rectangle, by simply replacing the instances if
they are the same type)
Dynamic, highly parameterized software is hard to read and understand.
Use composition as recommended by design patterns
To Conclude
128
129
INHERITANCE AND
COMPOSITION WORK
TOGETHER
DON’T OVER USE
INHERITANCE TO ACHIEVE
NEW FUNCTIONALITY
DESIGNS ARE MADE MORE
REUSABLE AND SIMPLER BY
DEPENDING MORE ON
OBJECT COMPOSITION.
Designing for
change
130
Designing for Change
131
A DESIGN THAT DOES NOT TAKE
CHANGE INTO ACCOUNT RISKS A
MAJOR REDESIGN IN THE FUTURE.
EACH DESIGN PATTERN LETS SOME
ASPECT OF SYSTEM STRUCTURE
VARY INDEPENDENTLY OF THE
OTHER ASPECTS
MORE ROBUST SYSTEM TO A
PARTICULAR TYPE OF CHANGE.
Common causes
for changes
132
133
1. Creating an object by specifying a class explicitly
(committing to an implementation not to an interface)
• Solution: create an object indirectly;
• Examples: Abstract Factory, Factory Method, Prototype patterns
2. Dependence on specific operations. (committing to
one way of responding to a request)
• Solution: avoid hard-coded request;
• Examples: Chain of responsibility, Command patterns
134
3. Dependence on hardware and software platform. Porting problem
from one platform to the other, different OS or different Hardware
• Solution: Design with no (limited) platform dependencies;
• Examples: Abstract factory and Bridge patterns
4. Dependence on object representations or implementations
• Solution: Hide this information from clients;
• Examples: Abstract Factory, Bridge, Memento, Proxy patterns
5. Algorithmic dependencies
• Solution: Algorithms must be isolated;
• Examples: Strategy, Builder, Iterator, Visitor and Template Method
135
6. Tight coupling – Changes in one class requires changes in many
others.
• Solution: Loose coupling, abstract coupling and layering;
• Examples: Abstract Factory, Bridge, Chain of Responsibility, Command, Façade,
Mediator, Observer
7. Extending functionality by subclassing
• Solution: Object Composition and delegation;
• Examples: Composite, Decorator, Observer, Bridge, …
8. Inability to change classes (no access to source, commercial class
library)
• Solution: use Adapter, Decorator, and Visitor

Mais conteĂşdo relacionado

Mais procurados

Design Pattern
Design PatternDesign Pattern
Design Patternwiradikusuma
 
Design patterns
Design patternsDesign patterns
Design patternsabhisheksagi
 
Gof design patterns
Gof design patternsGof design patterns
Gof design patternsSrikanth R Vaka
 
Design patterns ppt
Design patterns pptDesign patterns ppt
Design patterns pptAman Jain
 
Adapter pattern
Adapter patternAdapter pattern
Adapter patternShakil Ahmed
 
Design Patterns
Design PatternsDesign Patterns
Design PatternsAnuja Arosha
 
Software Engineering - chp4- design patterns
Software Engineering - chp4- design patternsSoftware Engineering - chp4- design patterns
Software Engineering - chp4- design patternsLilia Sfaxi
 
Unified Modeling Language
Unified Modeling LanguageUnified Modeling Language
Unified Modeling LanguageDebajyoti Biswas
 
Gof design pattern
Gof design patternGof design pattern
Gof design patternnaveen kumar
 
Java Design Patterns Tutorial | Edureka
Java Design Patterns Tutorial | EdurekaJava Design Patterns Tutorial | Edureka
Java Design Patterns Tutorial | EdurekaEdureka!
 
Design Pattern in Software Engineering
Design Pattern in Software EngineeringDesign Pattern in Software Engineering
Design Pattern in Software EngineeringManish Kumar
 
Software design patterns ppt
Software design patterns pptSoftware design patterns ppt
Software design patterns pptmkruthika
 
PATTERNS04 - Structural Design Patterns
PATTERNS04 - Structural Design PatternsPATTERNS04 - Structural Design Patterns
PATTERNS04 - Structural Design PatternsMichael Heron
 
Factory Design Pattern
Factory Design PatternFactory Design Pattern
Factory Design PatternJaswant Singh
 
Object Oriented Testing
Object Oriented TestingObject Oriented Testing
Object Oriented TestingAMITJain879
 
Design Concept software engineering
Design Concept software engineeringDesign Concept software engineering
Design Concept software engineeringDarshit Metaliya
 
Creational pattern
Creational patternCreational pattern
Creational patternHimanshu
 
An Introduction to Software Architecture
An Introduction to Software ArchitectureAn Introduction to Software Architecture
An Introduction to Software ArchitectureRahimLotfi
 

Mais procurados (20)

Design Pattern
Design PatternDesign Pattern
Design Pattern
 
Design patterns
Design patternsDesign patterns
Design patterns
 
Gof design patterns
Gof design patternsGof design patterns
Gof design patterns
 
Design patterns ppt
Design patterns pptDesign patterns ppt
Design patterns ppt
 
Adapter pattern
Adapter patternAdapter pattern
Adapter pattern
 
Design Patterns
Design PatternsDesign Patterns
Design Patterns
 
Software Engineering - chp4- design patterns
Software Engineering - chp4- design patternsSoftware Engineering - chp4- design patterns
Software Engineering - chp4- design patterns
 
Unified Modeling Language
Unified Modeling LanguageUnified Modeling Language
Unified Modeling Language
 
Gof design pattern
Gof design patternGof design pattern
Gof design pattern
 
Java Design Patterns Tutorial | Edureka
Java Design Patterns Tutorial | EdurekaJava Design Patterns Tutorial | Edureka
Java Design Patterns Tutorial | Edureka
 
Design Pattern in Software Engineering
Design Pattern in Software EngineeringDesign Pattern in Software Engineering
Design Pattern in Software Engineering
 
Software design patterns ppt
Software design patterns pptSoftware design patterns ppt
Software design patterns ppt
 
UML
UMLUML
UML
 
Facade Pattern
Facade PatternFacade Pattern
Facade Pattern
 
PATTERNS04 - Structural Design Patterns
PATTERNS04 - Structural Design PatternsPATTERNS04 - Structural Design Patterns
PATTERNS04 - Structural Design Patterns
 
Factory Design Pattern
Factory Design PatternFactory Design Pattern
Factory Design Pattern
 
Object Oriented Testing
Object Oriented TestingObject Oriented Testing
Object Oriented Testing
 
Design Concept software engineering
Design Concept software engineeringDesign Concept software engineering
Design Concept software engineering
 
Creational pattern
Creational patternCreational pattern
Creational pattern
 
An Introduction to Software Architecture
An Introduction to Software ArchitectureAn Introduction to Software Architecture
An Introduction to Software Architecture
 

Semelhante a Design Patterns - General Introduction

Design engineering
Design engineeringDesign engineering
Design engineeringPreeti Mishra
 
Design Concepts in Software Engineering-1.pptx
Design Concepts in Software Engineering-1.pptxDesign Concepts in Software Engineering-1.pptx
Design Concepts in Software Engineering-1.pptxKarthigaiSelviS3
 
SADP PPTs of all modules - Shanthi D.L.pdf
SADP PPTs of all modules - Shanthi D.L.pdfSADP PPTs of all modules - Shanthi D.L.pdf
SADP PPTs of all modules - Shanthi D.L.pdfB.T.L.I.T
 
Cse 6007 fall2012
Cse 6007 fall2012Cse 6007 fall2012
Cse 6007 fall2012rhrashel
 
Oose unit 4 ppt
Oose unit 4 pptOose unit 4 ppt
Oose unit 4 pptDr VISU P
 
Module 2 design patterns-2
Module 2   design patterns-2Module 2   design patterns-2
Module 2 design patterns-2Ankit Dubey
 
UNIT 01 SMD.pptx
UNIT 01 SMD.pptxUNIT 01 SMD.pptx
UNIT 01 SMD.pptxKalpna Saharan
 
OOSE Unit 4 PPT.ppt
OOSE Unit 4 PPT.pptOOSE Unit 4 PPT.ppt
OOSE Unit 4 PPT.pptitadmin33
 
UNIT-4design-concepts-se-pressman-ppt.PPT
UNIT-4design-concepts-se-pressman-ppt.PPTUNIT-4design-concepts-se-pressman-ppt.PPT
UNIT-4design-concepts-se-pressman-ppt.PPTmalathijanapati1
 
Modern software architect post the agile wave
Modern software architect post the agile waveModern software architect post the agile wave
Modern software architect post the agile waveNiels Bech Nielsen
 
12266422.ppt
12266422.ppt12266422.ppt
12266422.pptCSEC5
 
04 designing architectures
04 designing architectures04 designing architectures
04 designing architecturesMajong DevJfu
 
Design and Implementation in Software Engineering
Design and Implementation in Software EngineeringDesign and Implementation in Software Engineering
Design and Implementation in Software EngineeringKourosh Sajjadi
 
OOSAD Chapter 6 Object Oriented Design.pptx
OOSAD Chapter 6 Object Oriented Design.pptxOOSAD Chapter 6 Object Oriented Design.pptx
OOSAD Chapter 6 Object Oriented Design.pptxBereketMuniye
 
Designpattern
DesignpatternDesignpattern
DesignpatternSrikrishna k
 
Software Patterns
Software PatternsSoftware Patterns
Software Patternskim.mens
 
Design pattern in android
Design pattern in androidDesign pattern in android
Design pattern in androidJay Kumarr
 
Traditional Process Models
Traditional Process ModelsTraditional Process Models
Traditional Process ModelsAhsan Rahim
 

Semelhante a Design Patterns - General Introduction (20)

Design engineering
Design engineeringDesign engineering
Design engineering
 
Design Concepts in Software Engineering-1.pptx
Design Concepts in Software Engineering-1.pptxDesign Concepts in Software Engineering-1.pptx
Design Concepts in Software Engineering-1.pptx
 
SADP PPTs of all modules - Shanthi D.L.pdf
SADP PPTs of all modules - Shanthi D.L.pdfSADP PPTs of all modules - Shanthi D.L.pdf
SADP PPTs of all modules - Shanthi D.L.pdf
 
Cse 6007 fall2012
Cse 6007 fall2012Cse 6007 fall2012
Cse 6007 fall2012
 
Oose unit 4 ppt
Oose unit 4 pptOose unit 4 ppt
Oose unit 4 ppt
 
Module 2 design patterns-2
Module 2   design patterns-2Module 2   design patterns-2
Module 2 design patterns-2
 
Ch 9-design-engineering
Ch 9-design-engineeringCh 9-design-engineering
Ch 9-design-engineering
 
UNIT 01 SMD.pptx
UNIT 01 SMD.pptxUNIT 01 SMD.pptx
UNIT 01 SMD.pptx
 
OOSE Unit 4 PPT.ppt
OOSE Unit 4 PPT.pptOOSE Unit 4 PPT.ppt
OOSE Unit 4 PPT.ppt
 
CHAPTER12.ppt
CHAPTER12.pptCHAPTER12.ppt
CHAPTER12.ppt
 
UNIT-4design-concepts-se-pressman-ppt.PPT
UNIT-4design-concepts-se-pressman-ppt.PPTUNIT-4design-concepts-se-pressman-ppt.PPT
UNIT-4design-concepts-se-pressman-ppt.PPT
 
Modern software architect post the agile wave
Modern software architect post the agile waveModern software architect post the agile wave
Modern software architect post the agile wave
 
12266422.ppt
12266422.ppt12266422.ppt
12266422.ppt
 
04 designing architectures
04 designing architectures04 designing architectures
04 designing architectures
 
Design and Implementation in Software Engineering
Design and Implementation in Software EngineeringDesign and Implementation in Software Engineering
Design and Implementation in Software Engineering
 
OOSAD Chapter 6 Object Oriented Design.pptx
OOSAD Chapter 6 Object Oriented Design.pptxOOSAD Chapter 6 Object Oriented Design.pptx
OOSAD Chapter 6 Object Oriented Design.pptx
 
Designpattern
DesignpatternDesignpattern
Designpattern
 
Software Patterns
Software PatternsSoftware Patterns
Software Patterns
 
Design pattern in android
Design pattern in androidDesign pattern in android
Design pattern in android
 
Traditional Process Models
Traditional Process ModelsTraditional Process Models
Traditional Process Models
 

Último

Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsArshad QA
 
Active Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdfActive Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdfCionsystems
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...MyIntelliSource, Inc.
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVshikhaohhpro
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...OnePlan Solutions
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software DevelopersVinodh Ram
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfkalichargn70th171
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providermohitmore19
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxbodapatigopi8531
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsAlberto GonzĂĄlez Trastoy
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...panagenda
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about usDynamic Netsoft
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comFatema Valibhai
 
Test Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and BackendTest Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and BackendArshad QA
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsJhone kinadey
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionSolGuruz
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️Delhi Call girls
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfWilly Marroquin (WillyDevNET)
 

Último (20)

Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
Active Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdfActive Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdf
 
Exploring iOS App Development: Simplifying the Process
Exploring iOS App Development: Simplifying the ProcessExploring iOS App Development: Simplifying the Process
Exploring iOS App Development: Simplifying the Process
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software Developers
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptx
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about us
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
Test Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and BackendTest Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and Backend
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with Precision
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS LiveVip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 

Design Patterns - General Introduction

  • 1. CPIT-252 DESIGN PATTERNS Teacher: Dr. Asma Cherif Office room: 144S email: acherif@kau.edu.sa IT dept. Course Coordinator: Dr. Asma Cherif 1
  • 2. REFERENCES Many resources have been used to build this course, if you notice any missing reference please contact me at acherif@kau.edu.sa • GoF book • Laurent Audibert (developpez.com) • Dr. Birgit Demuth (OCL) • Dr. K.M Anderson • Head First Collection • Software engineering, Ian Sommerville, ch2- quality management • www.newthinktank.com • https://sourcemaking.com • Derek Banas youtube channel 2
  • 3. GENERAL INTRODUCTION Course description Course outline Course objectives Mark distribution References
  • 4. Course Objectives 1. Generate code from class diagrams and vice versa (i) 2. Identify any GoF creational design patterns for code or scenario or design (k) 3. Design and implement GoF creational design patterns (c) 4. Identify any GoF structural design patterns for code or scenario or design (k) 5. Design and implement GoF structural design patterns (c) 6. Identify any GoF behavioural design patterns for code or scenario or design (k) 7. Design and implement GoF behavioural design patterns (c) 8. Design and Implement an application that simulate a medium size project as part of a group (l) 9. Detect the appropriate design patterns in class diagrams (b) 10. Recognize the design patterns from code (k) 11. Produce a pattern based design that maps the requirements of a given scenario using design patterns (k) 12. Implement code that maps the requirements of a given scenario or designs (c) 13. Evaluate the quality of software design using ISO25001 standard (m)
  • 5. Textbooks • Len Bass, Paul Clements, Rick Kazman, "Software Architecture in Practice", Addison-Wesley Professional; 2 edition (2003) • Erich Gamma, John Vlissides, Ralph Johnson, and Richard Helm, “Design Patterns: Elements of Reusable Object-Oriented Software”, (1994) 5
  • 6. DESIGN Design - Analysis vs Design - Structured vs OO Design - Architectural Design - Design Patterns
  • 7. What is a design? • Formulate the maximum alternative solutions of the problem and select the best one. • Design Possibilities : Algorithmic strategy Decomposition of a system Abstract function hierarchy 7
  • 8. 8 Types of design Logical Forms and Reports Interfaces and Dialog Physical Creating database, tables and fields Developing the logic of the code using the algorithm Hierarchical or system structure design
  • 9. Why do we need design? 9 Provides an overall picture of the system Allows us to focus on one thing at a time Provides concept reuse (NOT code reuse) Simplify implementation Assesses quality
  • 10. Design & quality 10 The design must implement all of the explicit (clear) requirements contained in the analysis model, and it must accommodate all of the implicit (hidden) requirements desired by the customer. The design must be a readable, understandable guide for developers, code generators and testers. The design should provide a complete picture of the software.
  • 12. Structured Vs OO design 12 Structured Design Object Oriented Design Basic components functions/procedures classes which include state (behaviors) and functions Component relationships one function calls other functions. One class uses other classes to help it fulfill its responsibilities (by its methods calling methods in the other classes) Inheritance Classes grouped into packages/subsystems Design Strategy  Top level function corresponds to program requirements  Define this in terms of less abstract functions  Continue on down until all functions are concrete  Refactoring: go back and re-design higher level functions if design becomes ugly Identify basic objects/concepts in application domain, and use these as foundation classes Select a design architecture Add additional classes for desired functionality Abstract out super classes to facilitate understanding and possible reuse Refactor as necessary
  • 13. Analysis and Design (What and How) • The analysis model analyses the problem in the problem domain, while the design model analyses the solution in the solution domain.
  • 14. Example (structured Design) 14 Analysis DFD Design (main program/subprogram architectural pattern)
  • 16. What is a pattern? • A pattern is a model or design used as a guide in needlework and other crafts • Synonymous: • Sample, specimen, swatch 16
  • 17. What is a pattern? 17 Pattern is a structure or template that is designed to provide solution of a specific problem. “A 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 the same way twice.”- Christopher Alexander A pattern is a recurring solution to a standard problem, in a context.
  • 18. Pattern-based Design • A software designer begins with a requirements model that presents an abstract representation of the system. • The requirements model describes the problem set, establishes the context, and identifies the system of forces. 18
  • 19. Pattern-based design tasks 1. Examine the requirements model and develop a problem hierarchy. 2. Determine if a reliable pattern language has been developed for the problem domain. 3. Beginning with a broad problem, determine whether one or more architectural patterns are available for it. 4. Using the collaborations provided for the architectural pattern, examine subsystem or component level problems and search for appropriate patterns to address them. 5. Repeat steps 2 through 5 until all broad problems have been addressed. 19
  • 20. Effective design pattern A Design Pattern is effective when: 20 It solves a problem It is a proven concept The solution isn't obvious It describes a relationship Minimizes human intervention
  • 22. Architectural Design 22 Is an early stage of the system design process. It represents the link between specification and design processes. It is often carried out in parallel with some specification activities. Main objective: identifying the sub-systems making up a system and the framework for sub-system control and communication. Output: description of the software architecture.
  • 23. Architectural patterns Distributed Layered Event-driven Repository-centric Peer to peer Client Server ( maybe single , two , or three tiers) MVC (Model – View Controller)
  • 24. MVC (Model – View - Controller) • MVC is an architectural pattern used in software engineering that separates the application logic from business logic. • Used in web based applications mainly
  • 25. How MVC works? • The user interacts with the UI • (e.g., user presses a button) • A controller handles the input event from the user interface. • The controller accesses the model, possibly updating it in a way appropriate to the user's action. • The view uses the model to generate an appropriate user interface • (e.g., view produces a screen listing the shopping cart contents). • The view gets its own data from the model. The model has no direct knowledge of the view.
  • 26. Common Design Mistakes 26 Not enough time has been spent to understand the underlying problem, its context and forces, and as a consequence, you select a pattern that looks right, but is inappropriate for the solution required. Once the wrong pattern is selected, you refuse to see your error and force fit the pattern. In other cases, the problem has forces that are not considered by the pattern you’ve chosen, resulting in a poor or wrong fit. Sometimes a pattern is applied too exactly and the required adaptations for your problem space are not implemented.
  • 27. Design Patterns and OOP: why do we need patterns? • OO approach divides the application to smaller, simpler and reusable entities. • However, OO approach can complexify the application if the way you divide your code does not follow any rule. • Spagetti effect • Ex: an application with 40000 lines of code, no architecture  the application can turn to be difficult to manage which leads to the emergence of bugs that are difficult to correct (dominos effect) • To avoid the problem another level of OO design should be followed • Design patterns 27
  • 28. What is a design pattern? • Design pattern is a widely accepted solution to a recurring design problem in OOP • A design pattern describes how to structure classes to meet a given requirement • Provides a general blueprint to follow when implementing part of a program • Does not describe how to structure the entire application • Does not describe specific algorithms • Focuses on relationships between classes • Made popular by Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides (authors of design patterns: elements of reusable object-oriented software) 28
  • 29. 29 Benefits of design patterns Learn from community wisdom Determine implementation faster Make code more readable to other programmers Give design structures explicit names Facilitate refactoring
  • 30. Types of design patterns Creational Patterns provide a way to create objects while hiding the creation logic, rather than instantiating objects directly using new operator. This gives program more flexibility in deciding which objects need to be created for a given use case. Structural Patterns concern class and object composition. Concept of inheritance is used to compose interfaces and define ways to compose objects to obtain new functionalities. Behavioral Patterns These design patterns are specifically concerned with communication between objects. 30
  • 31. OO DESIGN REVIEW Pillars of OOP- Class diagram – Interface - relationships between classes
  • 32. OO Design review 32 The main concept in OOP is the class. A class groups data (attributes) and treatments (methods). A class is an abstraction describing how objects act. An object is an instance of a class. • It is created in the run time with the new operator. Elements in OOP have a scope and a visibility. The visibility can be private/public/protected/package
  • 33. The 4 pillars of OOP Abstraction Encapsulation Polymorphism Inheritance OOP 33
  • 34. Class Diagram • The most important diagram in OOD (obligatory). • Use case Vs class: • Use cases diagram illustrates the system according to actors point of view while • The class diagram illustrates the internal structure of the system. It gives an abtract representation of system objects that will intercat to accomplish uses cases. • Gives a static view of the system. • Main elements: • Classes • The relation between classes • association • generalization • dependency • realization 34
  • 35. 35 Class Instance variable methodsfields Class variable Other functionsconstructor Setter/getter Non static static private public Parameter passing: 1. primitive type: by value 2. reference type: also by value (java)
  • 37. Methods • Overloading (be careful the difference is not in the return type only) • Class method : static method • Cannot use instance variables (non static fields) • Cannot call non static methods • Abstract method: is not implemented • A class that has at least one abstract method should be declared abstract 37 abstract abstract *A subclass of an abstract superclass should be declared abstract if it does not implement the abstract inherited methods
  • 39. Relationship between classes 39 Article Order Association Article Order Directed Association Employee 0..* 0..1 supervisor subordinate Reflexive Association Multiplicity Role Student Course Enrollment date enroll drop() cancel() 0..* 1..* Association class Library Book Aggregation Book Page Composition Account CheckingAccount Inheritance Printer PrinterSetup Realization PrinterSetup Realization Printer Order PaymentSystem Dependency
  • 41. 41 Article Order Association You can give a name and a direction to the association
  • 45. • A class can have a relationship with other classes. • The main relation is the inheritance (generalization/specialization). 45 Person Student Professor superclass subclasssubclass generalization specialization Account CheckingAccount Inheritance
  • 46. • A subclass inherits the fields and methods of the super class • A subclass can add its own fields and methods (specialization) • A subclass can redefine an inherited method (Overriding) 46 Account CheckingAccount Inheritance
  • 47. • Some times you can’t implement all the details in the super class • A superclass is abstract when it has at least one abstract method (without implementation) • The subclass should implement the abstract method (override) 47 Account CheckingAccount Inheritance
  • 48. • An interface in java is a design of a class. • It has static constants and abstract methods only. • The interface allows to achieve fully abstraction: no method body. • Allows multiple inheritance in Java. • Java Interface also represents IS-A relationship. • Interface cannot be instantiated like abstract class. 48 Printer PrinterSetup Realization PrinterSetup Printer
  • 49. A class implements an interface, if the class is not abstract, it should override the methods of the interface 49 Printer PrinterSetup Realization PrinterSetup Printer
  • 50. • A class implements an interface • A class extends a superclass • An interface extends another interface 50 Printer PrinterSetup Realization PrinterSetup Printer
  • 51. Printer PrinterSetup Realization PrinterSetup Printer Abstract class Interface 1) Abstract class can have abstract and non- abstract methods. Interface can have only abstract methods. 2) Abstract class doesn't support multiple inheritance. Interface supports multiple inheritance. 3) Abstract class can have final, non-final, static and non-static variables. Interface has only static and final variables. 4) Abstract class can have static methods, main method and constructor. Interface can't have static methods, main method or constructor. 5) Abstract class can provide the implementation of interface. Interface can't provide the implementation of abstract class. 6) The abstract keyword is used to declare abstract class. The interface keyword is used to declare interface. 7) Example: public class Shape{ public abstract void draw(); } Example: public interface Drawable{ void draw(); } 52
  • 52. • The dependency means that class A uses class B, but that class A does not contain an instance of class B as part of its own state. • It also means that if class B’s interface changes it will likely impact class A and require it to change. • You would use dependency to indicate that: • class A receives an instance of class B as a parameter to at least one of its methods. • class A creates an instance of class B local to one of its methods. • You would not, however, use dependency to indicate that class A declares an instance variable of class B. 53 Order PaymentSystem Dependency
  • 55. • An aggregation is a special kind of association • Instance of aggregator (Library) contains a reference to an instance of aggregated (Book) as part of the aggregator’s state, but the use of the specific instance of the aggregated is or may be shared among other aggregators (!= Library). • A shared association means that the lifetime of the aggregated object (the instance of Book), is outside the scope of the referencing object.  when a specific instance of the aggregator goes out of scope (garbage collected), the instance of the aggregated does not necessarily go out of scope. 56 Library Book Aggregation
  • 58. Aggregation Vs Composition • Lifetime of the instance 59
  • 59. Reverse Engineering • Reverse Engineer existing Applications consists in generating UML Models from source code (or binary files) to facilitate analysis, enhancement, or reuse • Hand-written or legacy source code can be difficult to understand. • Some projects incorporate binary or byte-code files that also require analysis. • The original developer may no longer be available, or may be development was assigned in pieces and no single individual knows the entire project. 60
  • 61. OCL • Developed at IBM in 1995 originally as a business engineering language • Adopted as a formal specification language within UML • Part of the official UML standard (from version 1.1 on) • Used to complement UML diagrams • Extends the Unified Modeling Language (UML) • Formal language for the definition of constraints and queries on UML models • Add precise semantics to visual (UML-) models 62
  • 63. 64 “A constraint is a restriction on one or more values of (part of) an object-oriented model or system.“ A constraint is formulated on the level of classes, but its semantics is applied on the level of objects originally formulated in the syntactic context of a UML model (i.e a set of UML diagrams)
  • 64. 65 What are the main types?
  • 65. 66 Three main elements 1.Invariant 1.Precondition 1.Postcondition
  • 66. 1. Invariant • An invariant is a constraint that should be true for an object during its complete lifetime. • Represents rules that should hold for the real-life objects after which the software objects are modeled.
  • 67. context Meeting inv: self.end > self.start 68
  • 68. Examples • context Meeting inv: self.end > self.start • context Meeting inv: end > start • context Meeting inv startEndConstraint: self.end > self.start "self" always refers to the object identifier from which the constraint is evaluated. Names can be given to the constraint 69
  • 69. Exercise Write the OCL statement to specify that the age is greater than 18. • Context Employee inv : age >18 • Context Employee inv : self.age >18 • Context Employee inv AgeCST: age >18 70 Employee name: String age: int
  • 70. Precondition/Postcondition 71 Constraints that specify the applicability and effect of an operation without stating an algorithm or implementation Are attached to an operation in a class diagram Allow a more complete specification of a system
  • 71. 2. Precondition • It is a constraint that must be true just prior to the execution of an operation
  • 72. Example 73 context Meeting::shift(d:Integer) pre: self.isConfirmed = false context Meeting::shift(d:Integer) pre: d>0 context Meeting::shift(d:Integer) pre: self.isConfirmed = false and d>0
  • 73. 3. Postcondition • It is a constraint that must be true just after the execution of an operation • Postconditions are the way how the actual effect of an operation is described in OCL.
  • 75. Main Keywords 76 Result • refers to the result of the operation • context Meeting::duration():Integer post: result = self.end – self.start @pre • is to be evaluated in the original state -- before execution of the operation • is only allowed in postconditions • context Meeting :: shift(d:Integer) post: start = start@pre +d and end = end@pre + d
  • 76. OCL Expressions 77 Boolean expressions •Standard library of primitive types and associated operations • Basic types: Boolean, Integer, Real, String Collection types •Set •Ordered Set •Bag •Sequence
  • 77. User defined types (OCLType) • Class type: • A class has the following Features: • Attributes (start) • Operations (duration()) • Class attributes (Date::today ) • Class operations • Association ends (navigation expressions) • Enumeration type (e.g. Gender, Gender::male) 78
  • 79. 80 x.y Obtain the property y of object x A property can be an attribute A property can be the set of objects at the end of an association
  • 80. 81 c->f Apply the built in OCL function f to collection c Context Meeting inv : self.participants -> size()>2
  • 81. 82
  • 82. Navigation Expressions • Association ends (role names) used to navigate from one object in the model to another object. • Navigations are treated as attributes (dot-Notation). • The type of a navigation expression is either a • User defined type (association end with multiplicity at most 1) • Collection (association end with multiplicity > 1) 83
  • 83. Example User defined type context Meeting context Meeting inv: self.moderator.gender = Gender::female Collection context Meeting inv: self->collect(participants)->size()>=2 self.participants 84
  • 84. 85 And, or, =, <> Logical and, or, equal and not equal Context Person inv : self.participants -> size()>2
  • 85. 86 p implies q True if either q is true or p is false Context Person inv : isDriver = true implies age>=18
  • 86. Sample of operations on sets 88
  • 87. Exercise • Specify the requirements: • A vehicle owner age must be >=18 : Context vehicle inv: owner.age > = 18 • A car owner age must be >=18 :Context car inv: owner.age > = 18 • Nobody has more than 3 vehicles: Context Person inv: (fleet->size())<=3 • Calling birthday() increments the age of a person by 1: Context Person :: Birthday() post: age = age@pre+1 90
  • 89. What is Gang of Four (GOF)? • In 1994, four authors Erich Gamma, Richard Helm, Ralph Johnson and John Vlissides published a book titled Design Patterns - Elements of Reusable Object-Oriented Software which initiated the concept of Design Pattern in Software development. • These authors are known as Gang of Four (GOF). • According to GOF design patterns are primarily based on: • Program to an interface not an implementation • Favor object composition over inheritance 92
  • 90. Elements of Design Patterns Design patterns have 4 essential elements: • Pattern name: increases vocabulary of designers • Problem: intent, context, when to apply • Solution: UML-like structure, abstract code • Consequences: results and tradeoffs 93
  • 91. Describing Design Patterns • Pattern Name and Classification: A descriptive and unique name that helps in identifying and referring to the pattern. • Intent: A description of the goal behind the pattern and the reason for using it. • Motivation (Forces): A scenario consisting of a problem and a context in which this pattern can be used. • Applicability: Situations in which this pattern is usable; the context for the pattern. • Structure: A graphical representation of the pattern. Class diagrams and Interaction diagrams may be used for this purpose. • Participants: A listing of the classes and objects used in the pattern and their roles in the design. • Collaboration: A description of how classes and objects used in the pattern interact with each other. • Consequences: A description of the results, side effects, and tradeoffs caused by using the pattern. • Implementation: A description of an implementation of the pattern; the solution part of the pattern. • Sample Code: An illustration of how the pattern can be used in a programming language. • Known Uses: Examples of real usages of the pattern. • Related Patterns: Other patterns that have some relationship with the pattern; discussion of the differences between the pattern and similar patterns. 94
  • 92. Design Patterns are 95 Design Patterns are not Data structures (i.e., linked lists, hash tables) Complex domain-specific designs (for an entire application or subsystem)
  • 93. What are they? 96 “Descriptions of communicating objects and classes that are customized to solve a general design problem in a particular context.”
  • 94. Benefits of Design Patterns • enable large-scale reuse of software architectures • help to document systems • explicitly capture expert knowledge and design tradeoffs and make it more widely available • help improve developers communication 97
  • 95. Classification of design patterns GF DP classification purpose creational How to create objects while hiding the creation logic Deal with initializing and configuring classes and objects structural Define ways to compose objects to obtain new functionalities. Deal with decoupling interface and implementation of classes and objects behavioral Deal with dynamic interactions among societies of classes and objects How they distribute responsibility scope class Deal with relationships between classes and their subclasses Relationships established through inheritance, so they are fixed at compile time (static) object Deal with object relationships Relationships can be changed at runtime (dynamic) 98 11 5 7 4 20
  • 96. The Catalog of Design Patterns 99 Purpose Scope Creational Structural Behavioral Class Factory Method Adapter(class) Interpreter Template Method Object Abstract Factory Builder Prototype Singleton Adapter (object) Bridge Composite Decorator Façade Flyweight Proxy Chain of Responsibility Command Iterator Mediator Observer State Strategy Visitor
  • 97. Design Pattern Scope • Class Patterns (4) • Deal with relationships between classes and their subclasses • Relationships established through inheritance, so they are fixed at compile time (static) • Object patterns (20) • Deal with object relationships • Relationships can be changed at runtime (dynamic) 100
  • 98. General Introduction-Design Six types of design patterns 1. Creational class patterns defer some part of object creation to subclasses 2. Creational object patterns defer some part of object creation to another object 3. Structural class patterns use inheritance to compose classes 4. Structural object patterns describe ways to assemble objects 5. Behavioral class patterns use inheritance to describe algorithms and flow of control 6. Behavioral object patterns describe how a group of objects cooperate to perform a task that no single object can carry out alone 101
  • 99. Design patterns were introduced to solve design problems 102
  • 101. 104 The hard part about OO design is decomposing a system into objects Many factors are involved: encapsulation, granularity, dependency, performance, evolution, reusability, etc. Many objects come from the analysis model. But we often end up with classes that has no counterpart in the real world. Strict modeling of the world leads to a design that reflect today’s need and not necessarily future. Abstraction is a way to treat objects that do not have a physical counterpart. Design patterns help identify less obvious abstractions and objects that can capture them.
  • 103. 106 How do we decide what should be an object? In what granularity? Objects can vary in size and numbers. They can represent everything (hardware  entire application) Design Patterns address this issue. Example: Façade pattern describe how to present complete subsystems as objects.
  • 105. 108 Interface? Interface = set of signatures, operation signature = Name + return type + parameters A type is name used to denote a particular interface Interfaces are fundamental in OO systems Objects are known only through their interfaces. An object interface hides its implementation
  • 106. Design patterns help defining interfaces by determining the type of data that gets sent across interfaces. example: Memento pattern shows objects must define two interfaces: a restricted one that hold and copy mementos and another one that only original object can use to store and retrieve state. Design patterns specify relationships between interfaces.
  • 108. 111 Implementation? An object implementation is defined by its class. Object instantiations, Class hierarchy, inheritance, what should be the abstract classes and what should be concrete classes, etc..? Patterns such as Composite, Abstract factory, chain of responsibility address these issues.
  • 110. 1st good design principle: Program to an interface not to an implementation 113
  • 111. 114 Implementation? Class inheritance gives the ability to define new objects in terms of an old one. Get identical interfaces by inheriting from an abstract class. All classes derived from an abstract class simply override interfaces and therefore they can all respond to the requests to the abstract class (i.e they are all subtypes) Two benefits: 1- clients remain unaware of the specific type of objects they use. 2- clients remain unaware of the classes that implement these objects
  • 112. Consequences of the 1st principle • Don’t declare variables to be instances of concrete classes since clients need only know the abstract classes • Creational patterns ensure that your system is written in terms of interfaces, not implementations. 115
  • 113. 2nd Design principle: Favor Composition over Inheritance 116
  • 114. Pros and Cons of inheritance 117 CLASS INHERITANCE IS EASY TO USE AND EASY TO MODIFY (OVERRIDE) CANNOT CHANGE IMPLEMENTATION AT RUNTIME (IT IS DEFINED AT COMPILE TIME) WORSE IT BREAKS ENCAPSULATION ANY CHANGE TO PARENT IMPLEMENTATION WILL FORCE SUBCLASSES TO CHANGE.  MAKES REUSE OF SUBCLASSES VERY LIMITED.
  • 115. Inheritance weaken encapsulation 118 Any change to superclass will break code using subclass
  • 116. Can we solve this? How? 119
  • 117. Object composition 120 Object Composition is defined dynamically at runtime (unlike inheritance) through acquiring references to other objects does not break encapsulation Any object can be replaced with another (of same type) at runtime so much less implementation dependency
  • 119. Consequences of the 2nd principle • Helps keep each class encapsulated and focused on one task. • Classes and class hierarchies will remain small and more manageable. • A design with composition will have more objects and system behavior will depend on their interrelationship rather than defined in one class. • Allow to delegate a request 122
  • 121. 124 A WAY TO MAKING COMPOSITION POWERFUL FOR REUSE. TWO OBJECTS ARE INVOLVED IN HANDLING A REQUEST ONE OBJECT RECEIVES THE REQUEST, AND DELEGATES THE REQUEST TO BE HANDLED BY ITS DELEGATE.
  • 122. Example: Window and Rectangle objects 125 instead of using inheritance, by defining window as being a rectangle, it can have a rectangle as attribute
  • 124. 127 Delegation makes easy to compose behaviors at run-time (e.g. window can become circle instead of rectangle, by simply replacing the instances if they are the same type) Dynamic, highly parameterized software is hard to read and understand. Use composition as recommended by design patterns
  • 126. 129 INHERITANCE AND COMPOSITION WORK TOGETHER DON’T OVER USE INHERITANCE TO ACHIEVE NEW FUNCTIONALITY DESIGNS ARE MADE MORE REUSABLE AND SIMPLER BY DEPENDING MORE ON OBJECT COMPOSITION.
  • 128. Designing for Change 131 A DESIGN THAT DOES NOT TAKE CHANGE INTO ACCOUNT RISKS A MAJOR REDESIGN IN THE FUTURE. EACH DESIGN PATTERN LETS SOME ASPECT OF SYSTEM STRUCTURE VARY INDEPENDENTLY OF THE OTHER ASPECTS MORE ROBUST SYSTEM TO A PARTICULAR TYPE OF CHANGE.
  • 130. 133 1. Creating an object by specifying a class explicitly (committing to an implementation not to an interface) • Solution: create an object indirectly; • Examples: Abstract Factory, Factory Method, Prototype patterns 2. Dependence on specific operations. (committing to one way of responding to a request) • Solution: avoid hard-coded request; • Examples: Chain of responsibility, Command patterns
  • 131. 134 3. Dependence on hardware and software platform. Porting problem from one platform to the other, different OS or different Hardware • Solution: Design with no (limited) platform dependencies; • Examples: Abstract factory and Bridge patterns 4. Dependence on object representations or implementations • Solution: Hide this information from clients; • Examples: Abstract Factory, Bridge, Memento, Proxy patterns 5. Algorithmic dependencies • Solution: Algorithms must be isolated; • Examples: Strategy, Builder, Iterator, Visitor and Template Method
  • 132. 135 6. Tight coupling – Changes in one class requires changes in many others. • Solution: Loose coupling, abstract coupling and layering; • Examples: Abstract Factory, Bridge, Chain of Responsibility, Command, Façade, Mediator, Observer 7. Extending functionality by subclassing • Solution: Object Composition and delegation; • Examples: Composite, Decorator, Observer, Bridge, … 8. Inability to change classes (no access to source, commercial class library) • Solution: use Adapter, Decorator, and Visitor

Notas do Editor

  1. ghmhn
  2. 1.Abstraction Abstraction is a process of exposing essential feature of an entity while hiding other irrelevant detail. Why would you want to use abstraction? abstraction reduces code complexity and at the same time it makes your aesthetically pleasant. 2.Encapsulation We have to take in consideration that Encapsulation is somehow related to Data Hiding. Encapsulation is when you hide your modules internal data and all other implementation details/mechanism from other modules. it is also a way of restricting access to certain properties or component. Remember, Encapsulation is not data hiding, but Encapsulation leads to data hiding 3.Inheritance The ability of creating a new class from an existing class. Like ther word Inheritance literally means it is a practice of passing on property, titles, debts, rights and obligations upon the death of an individual. in OOP this is somehow true(Except the death of an individual) , where The base class(the existing class sometimes called as the Parent class) has properties and methods that will be inherited by the sub class(somtimes called a subtype or child class) and it can have additional properties or methods. Inheritance is also a way to use code of an existing objects. 4. Polymorphism Just like in biology, Polymorphism refers to the ability to take into different forms or stages.A subclass can define its own unique behaviour and still share the same functionalities or behavior of its parent/base class.Yes, you got it right, subclass can have their own behavior and share some behaviour from its parent class BUT!! not vice versa. A parent class cannot have the behaviour of its subclass.
  3. 12down voteaccepted A slash in front of an attribute means that the attribute is derived. The value of a derived attribute is calculated from the value of other model elemetns in the diagram. For instance, the accountBalance value can be derived from the list of payments and deposits made for that account (assuming that information about payments and deposits is stored in other classes in the diagram). The derivation rule for a derived attribute (i.e. how to compute its value) can be specified in natural language or more formally in OCL
  4. User defined type – Navigation from Meeting to moderator results in type Teammember Collection – Navigation von Meeting to participants results in type Set(Teammember)
  5. Context vehicle inv: owner.age > = 18 Context car inv: owner.age > = 18 Context Person inv: fleet->size()<=3 Context Person :: Birthday() post: age@pre = age@pre+1
  6. does not break encapsulation because objects are accessed solely through interfaces (but that means some effort on good interface design)