Вы находитесь на странице: 1из 60

www.1000projects.

com
www.chetanasprojects.com
www.campusmiles.com

Design Patterns & UML

1
Course Topics
1. Design Patterns
– What is Pattern?
– Design Pattern & Framework
– Creational Patterns
– Structural Patterns
– Behavioral Patterns
1. UML
– What is UML?
– Use Case Diagram
– Class Diagram
– Relationships Between Classes
– Sequence Diagram
– Activity Diagram
– Collaboration Diagram
1. Case Study
2
What is Pattern?
• Lets interpret following number series
• 1247234934444541
• For the time being, Don’t consider 4th digit
• 124 234 344 454
• 12 4 7 23 4 9 34 4 4 45 4 1
• First two digits are of sequential nature with 1 plus. Third digit is
fixed. Fourth digit having random value.
• First two digits are of sequential nature with 1 plus. Third digit is
fixed. Fourth digit having random value.
Keyword is: Repetition
“Each pattern describes a problem which occurs over and over
again in our environment and then describe the core 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”

3
Contd…
• A set of rules describing how to accomplish certain tasks in the
realm of software development.

• Identify and specify abstractions that are above the level of single
classes or instances, or of components.

• They are not usually written by single individuals: They are usually
discovered in several different programmers' works.
• Gang of Four (GoF)
– Erich Gamma
– Richard Helm
– Ralph Johnson
– John Vlissides

4
Why Design Pattern?
• Writing objects is easy.

• Designing how objects communicate is the new


challenge.

• Design Patterns are a set of tested approaches for


specifying these interactions.

5
Why Design Pattern?
• Designing OO software is hard.

• Designing reusable OO software is harder.


– Very difficult to get a “right” design the very first time.

• Get the design experience of an expert.

• Easy to understand and document the design

• Use applied and proven design techniques.

6
Design Pattern
• Solution to Problems that arise when
developing software within a particular context
Design Pattern = Problem (Recurring) / Solution pair in a Context
As specified by GOF:

Design Pattern

Creational Structural Behavioral

7
Design Pattern & Framework
• Design Pattern is a proven design solution for a recurring design problem
which arises in specific design context.
• A framework is an integrated set of classes that make up a reusable
design for a specific class of software.
– Ex : Compiler, graphical editor.
• Together, design patterns and frameworks help to improve software
quality and reduce development time e.g., reuse, extensibility, modularity,
performance

Design Pattern Vs Framework


• Design Patterns are more abstract than frameworks.
• Design Patterns are smaller architectural elements than frameworks (A
framework may contain several design patterns).
• Design Patterns are less application specialized than frameworks

8
Design Pattern Space
Gamma have classified each of design patterns in one of three
categories, depending upon whether it has to do with

• Creating a collection of objects in flexible ways ( Creational


Patterns)

• Representing a collection of related objects ( Structural


Patterns)

• Capturing behavior among a collection of objects ( Behavioral


Patterns )

9
Design Pattern Space
• Creational Patterns
– Deal with initializing and configuring classes and
objects.
– Make a system independent of how its objects are
created.
• Structural Patterns
– Deal with decoupling interface and implementation of
classes and objects.
• Behavioral Patterns
– Deal with dynamic interactions among societies of
classes and objects.
10
Contd…
Creational Structural Behavioral
Abstract Factory Adapter Chain of Responsibility
Builder Bridge Command
Factory Composite Interpreter
Prototype Decorator Iterator
Singleton Façade Mediator
Flyweight Memento
Proxy Observer
State
Strategy
Template
Visitor

11
Another Classification
• Class Patterns
– Relationships between classes and their sub-
classes
– Factory, Adapter, Interpreter, Template
• Object Patterns
– Object relationships which are created at runtime
and are more dynamic

12
Creational Pattern
• Creational design patterns abstract the instantiation
process.

• Client is independent of how its objects are created,


composed and represented.

• They give flexibility in what gets created, who


creates it, how it gets created and when.

13
Factory Pattern
• A Factory pattern is one that produces one of several possible classes
depending on data provided to it.
• Provides a simple decision making class that returns one of several
possible subclasses of an (abstract) base class depending on the data
provided.

When to Use:
• A class can’t anticipate which class of objects it must create.
Localizing the knowledge which class gets created.

• A class wants its sub-class to specify the objects it creates.

• Classes delegate responsibility of creation to one of several sub-


classes and localize the knowledge of which helper class to choose.

14
Factory Method

Define an interface for creating an object, but let subclasses decide which class
to instantiate. Factory method lets a class defer instantiation to subclasses.
15
Structural Pattern
• Concerned with how classes and objects are
composed to form larger structures
• Structural class patterns use inheritance to compose
interfaces or implementations
• Structural object patterns describe ways to compose
objects to realize new functionality.

16
Composite
• Compose objects into tree structures to represent
part-whole hierarchies. Composite lets clients treat
individual objects and compositions of objects
uniformly.
• It defines a class hierarchy of simple objects and
composite objects to be represented in one object.
• Employee (Manager, Programmer)
• Node & Leaf.

17
Composite Class Diagram

•Represent part-whole hierarchies.

•Enable clients to ignore the differences between individual objects and


compositions of objects. 18
Decorator Class Diagram
•Attach additional responsibilities to an object dynamically.
•Decorators provide a flexible alternative to sub classing for
extending functionality.

19
Decorator
•Add additional functionality to InputStream.

•Keep adding/removing functionalities dynamically.

•DataInputStream dis = new DataInputStream(new


BufferedInputStream(new FilterInputStream(“somefile”) ) ) )

Applicability

•Add / remove responsibilities to Objects dynamically and transparently

•When extension by sub-classing is impractical – Large number of sub-


classes required to support many combinations
DataBufferInputStream
LineNumberPushBackInputStream

20
Behavioral Patterns
•Concerned with algorithms and assignment of
responsibilities between objects.

•Describe patterns of communication between the


objects.

•Characterize flow control in the program

21
Chain of Responsibility
• A way of passing a request between a chain of
objects.

• Avoid coupling the sender of the request to its


receiver by giving more than one object a chance to
handle the request.
• Chain the receiving objects and pass the request
along the chain until an object handles it.

Example :
The most obvious example of the Chain of Responsibility is the class
inheritance structure itself. When a method is called, that method is
passed up the inheritance chain until the first parent class containing
that method is found.
22
Chain of Responsibility
Applicability

•More than one object may handle a request


and the handler isn’t known a priori. The
handler should be ascertained automatically.

•Issue request to one of several objects without


specifying the receiver explicitly.

•The set of objects that can handle a request


should be specified dynamically.
23
What is UML?
•UML stands for Unified Modeling Language.

•UML is a set of standard notations used for modeling


object oriented systems.

•UML has evolved through the work of Grady Booch,


James Rumbaugh, Ivar Jacobson and Rational Software
Corporation.

•UML helps to specify, visualize and document models


representing systems.

•UML is a industry standard for modeling application


systems.
24
Contd…
•UML model is methodology independent; i.e. UML can be
mapped for all the widespread methodologies.

•UML model can be either hardware and software platform


specific or hardware and software platform independent.

•UML model be either Programming language specific or


independent..

•UML has been accepted by Object Management Group


(OMG) as the standard for modeling OO systems.

•UML is the foundation of OMG’s model driven architecture


(MDA).
25
UML Modeling
• Modeling is a highly creative process through which a solution is
created iterating through the requirements.

• Provides standardization of models across the industry.


• Provides common language to Architects, developers and
business users.

• Human brain is more receptive to pictures than texts; hence


models convey lot more than pages of text

• Modeling is essential part of large projects and is useful for small


and medium size projects.

• UML provides support in each phase of OOAD software life


cycle.
26
UML Modeling
• Provides support for taking a holistic view of the system
through the various models representing logical,
implementation, deployment, process and use case views.

• Supports model driven architecture (MDA).

• Enhances speed of project by providing code generation


from the model.

• Reverse engineering features of the modeling tool helps in


understanding the existing systems.

• Has support for platform specific (PSM) as well as platform


independent models (PIM)
27
Use Case
This is the most important model used for the Object
oriented analysis. This denotes functionality of system
using actors and use cases. This is also used for
understanding the boundary of the system.

28
Use Case Diagram Symbols/Notations
Symbols/ Notation Description

System scope This is represented by a rectangular hollow box. This is used to define the boundary of the
system.

Use case This is represented by an ellipse shape. This is used to represent a set of transactions that
provides some tangible value to the actors.

Maintain System

Actor An actor is represented by a stick man. An actor interacts with the use case to get some tangible
value from the system.

end user

Links Actors are linked with the use cases when either they contribute to the use case or get some
benefits from the use case. Use cases are linked with other use cases via includes and extends
relationship.
Includes If some functionality is common to multiple use cases then it can be separated as a use case and
denoted by <<includes>> stereotype.
Extends If there are two use cases in which one use case has a special type is functionality extending the
other use case then it is represented by using extension point and denoted by <<extends>>
stereotype.
Packages Packages are used to group the use cases. Package is represented as Insurance

29
Use Case Diagram

Create Sales Data


<<include>>

Salesman
Browse Catalog
<<include>>
<<extend>>
Update Sales Data

Browse Holiday Special Catalog

30
Sequence Diagram Symbols/Notations
Class roles The class role is a view of the class that helps achieve a particular
functionality.
Actor The notation and use of actor is same as that described in the use
case diagram. The actors start a sequence by acting upon the system.
Represented the same way as the actors of the use case diagram.

Message A message is ideally a method call between two classes.


Lifeline Lifeline denotes the life span of a method call. Unless the method
implementation is asynchronous, all the calls block till the child calls
return. This diagram helps to see if any object is blocked unnecessarily
during a call which can be avoided.
Loops These are self calls; when a object makes a call to itself to get some
information.

31
Sequence Diagram

OrderEntryWindow Order OrderLine Item


: OrderEntryClerk
start() prepare() prepare() checkLevel()
isReorderLevel()

reOrder()

if reorder level is
reached

32
Relationships Between Classes

33
Relationships Between Classes

Note:
Note: For
For details,
details, please
please refer
refer http://en.wikipedia.org/wiki/Class_diagram#Association
34
Relationships Between Classes
• Association

• Dependency

• Aggregation

• Generalization

Note: For details, please refer http://en.wikipedia.org/wiki/Class_diagram#Association


35
Association
An association represents a family of links. Binary associations (with two
ends) are normally represented as a line, which each end connected to a
class box. Higher order associations can be drawn with more than two
ends. In such cases, the ends are connected to a central diamond.

When two classes are connected to each other in any way, an association
relation is established. For example: A "student studies in a college"
association can be shown as:

Student College

Note: For details, please refer http://en.wikipedia.org/wiki/Class_diagram#Association


36
Dependency
A dependency exists between two defined elements if a change to the
definition of one would result in a change to the other. This is indicated by
a dashed arrow pointing from the dependent to the independent element.
Several named varieties exist. A dependency can be between instances,
classes, or both.

Person House

Note: For details, please refer http://en.wikipedia.org/wiki/Class_diagram#Association


37
Aggregation
• Aggregation is a variant of the "has a" or association relationship; composition
is more specific than aggregation.

• An aggregation may not involve more than two classes.

• Aggregation can occur when a class is a collection or container of other


classes.

• In UML, it is graphically represented as a clear diamond shape on the


containing class end of the tree of lines that connect contained class(es) to the
containing class.

Note: For details, please refer http://en.wikipedia.org/wiki/Class_diagram#Association


38
Generalization
• The generalization relationship indicates that one of the two related
classes (the supertype) is considered to be a more general form of the
other (the subtype).

• The UML graphical representation of a Generalization is a hollow


triangle shape on the supertype end of the line that connects it to one
or more subtypes.

• The generalization relationship is also known as the inheritance or "is


a" relationship. e.g., A human is a mammal, a mammal is an animal.

• The supertype in the generalization relationship is also known as the


"parent", superclass, base class, or base type.

• The subtype in the generalization relationship is also known as the


"child", subclass, derived class, derived type, inheriting class, or
inheriting type.
Note: For details, please refer http://en.wikipedia.org/wiki/Class_diagram#Association
39
Generalization

Note: For details, please refer http://en.wikipedia.org/wiki/Class_diagram#Association


40
Class Diagram

41
Activity Diagram Symbols/Notations
Activity This is represented by a rectangle whose vertical sides are represented as
semi-circles.
This is used to represent activity as the name suggests.
Receiv
eorder

Action flow Represented by lines with arrowheads. These are used to show how the
actions change the system behavior.
Initial state Notation and usage are same as that of the Statechart diagram.
End state Notation and usage are same as that of the Statechart diagram.
Swim lanes Swim lanes are represented by vertical bars with titles that divide the activity
diagrams into various sections. These are used to denote the processes used
by various groups in an organization
Synchronization This is represented by a horizontal or vertical bar. This is used to denote
concurrent activities.

Decision Represented by a diamond and denotes a decision point.

States Notation and usage are same as that of the Statechart diagram. Denoted the
same way as the states in the state chart diagram.
42
Activity Diagram
Start

Receive Order

Fork

Activity

Fill Orders Send Invoice


Send Invoice

Branch

Overnight Regular Delivery Receive


Delivery Payment

Join

Join

Close orders

End
43
Case Study
Soccer Game engine is to model and simulate the soccer game in a controlled
environment with the help of various parameter. The idea is to identify, reconsider and
analyze the situation of a game based on input fed by the user and decision taken by
the game engine based on analysis done by game engine algorithm in real time.

The problem which are addressed here


• How to write an OOP and pattern based game engine which can be
changed and modified any time in future.

• It also address the problem of scalability and how future pattern can be
defined.

• How to adopt Design Pattern.

• How to provide reusable solutions for solving common design problems.

44
Case Study
Soccer Game Engine
• How you identify the entities in your game system

• How you identify the design problems.

• How you apply patterns to address your design specifications.

Identifying Entities :
First of all, you need to identify the objects you use in your game engine. For this,
you should visualize how the end user is going to use the system. Let us assume
that the end user is going to operate the game in the following sequence (let us
keep things simple).

• Start the game


• Select two teams
• Add or remove players to/from a team
• Pick a play ground
• Start the game
Note: For details, please refer http://www.codeproject.com/useritems/applyingpatterns.asp#An%20Overview%20Of%20Design%20Patterns 45
Contd…
Real world objects :

• Player who play the soccer


• Team with various players in it
• Ball which is handled by various players.
• PlayGround where the match takes place.
• Referee in the ground to control the game.

Logical objects :

• Game which defines a football game, which constitutes


teams, ball, referee, playground etc
• GameEngine to simulate a number of games at a time.
• TeamStrategy to decide a team's strategy while playing
46
Contd…
Abstract View ( High Level View )

47
Contd…
To be decided
• How these objects are structured.
• How they are created.
• Their behavior when they interact each other, to formulate the design
specifications.

Identifying the Design problem

• Ball
When the position of a ball changes, all the players and the referee should be
notified straight away.
• Team and TeamStrategy
When the game is in progress, the end user can change the strategy of his team
(E.g., From Attack to Defend)
• Player
A player in a team should have additional responsibilities, like Forward, Defender
etc, that can be assigned during the runtime.
• PlayGround
Each ground constitutes of gallery, ground surface, audience, etc - and each
ground has a different appearance. 48
Contd…
Identifying Patterns To Use
1: Addressing the design problems related with the 'Ball‘
First of all, take the specifications related to the ball. You need to design a
framework such that when the state (position) of the ball is changed, all the
players and the referee are notified regarding the new state (position) of the ball.
Now, let us generalize the problem

Specific Design Problem: "When the position of a ball changes, all the players
and the referee should be notified straight away."

Problem Generalized: "When a subject (in this case, the ball) changes, all its
dependents (in this case, the players) are notified and updated automatically."

Once you have such a design problem, you refer the GOF patterns - and
suddenly you may find out that you can apply the 'Observer' pattern to solve the
problem.

Observer Pattern: Define a one-to-many dependency between objects so that


when one object changes state, all its dependents are notified and updated
automatically. 49
Contd…
2: Addressing the design problems related with 'Team' And 'TeamStrategy‘

Next, we have to address the specifications related to the team and team
strategy. When the game is in progress, the end user can change the strategy of
his team (E.g., From Attack to Defend). This clearly means that we need to
separate the Team's Strategy from the Team that uses it.

Specific Design Problem: "When the game is in progress, the end user can
change the strategy of his team (E.g., From Attack to Defend)"

Problem Generalized: "We need to let the algorithm (TeamStrategy) vary


independently from clients (in this case, the Team) that use it."

Then, you can chose the 'Strategy' pattern to address the above design problem.

Strategy Pattern: Define a family of algorithms, encapsulate each one, and make
them interchangeable. Strategy lets the algorithm vary independently from
clients that use it.

50
Contd…
3: Addressing the design problems related with 'Player'
We need to assign responsibilities (like forward, defender etc) to each player
during run time. At this point, you can think about sub classing (i.e. inheritance) -
by creating a player class, and then inheriting classes like Forward, Defender etc
from the base class. But the disadvantage is that, when you do sub classing, you
cannot separate the responsibility of an object from its implementation.

I.e, In our case, sub classing is not the suitable method, because we need to
separate the responsibilities like 'Forward', 'Midfielder', 'Defender' etc from the
Player implementation. Because, a player can be a 'Forward' one time, and some
other time, the same player can be a 'Midfielder'.

Specific Design Problem: "A player in a team should have additional


responsibilities, like Forward, Defender etc, that can be assigned during the
runtime."

Problem Generalized: "We need to attach additional responsibilities (like


Forward, Midfielder etc) to the object (In this case, the Player) dynamically, with
out using sub classing"
Decorator pattern to address the above design problem. 51
Contd…
4: Addressing the design problems related with 'PlayGround'
We need to construct the ground in such a way that, the construction of the
ground can create different representations of the ground. I.e, a ground in Italy
may have different gallery structure and surface when compared to a ground in
England. But, the game engine may create both these grounds by calling the
same set of functions.

Specific Design Problem: "Each ground constitutes of gallery, ground surface,


audience, etc - and each ground has a different appearance."

Problem Generalized: "We need to separate the construction of an object


(ground) from its representation (the appearance of the ground) and we need to
use the same construction process to create different representations."

Builder Pattern: Separate the construction of a complex object from its


representation so that the same construction process can create different
representations.

52
Contd…
Understanding the Observer Pattern

53
Contd…
Now we will go ahead with first case (Addressing the design problems related with the 'Ball‘ , slide no. 47 )
Adapting the Observer Pattern

Observer Pattern 54
Contd…
Converting into Code

55
Contd…

56
Contd…

57
Contd…

58
Contd…

59
Contd…
Final Output

60

Вам также может понравиться