Sie sind auf Seite 1von 213

Object Oriented Analysis and Design CS6502

UNIT I (9)
Introduction to OOAD – What is OOAD? – What is UML? What are the United
process(UP) phases - Case study – the NextGen POS system, Inception -Use case
Modeling - Relating Use cases – include, extend and generalization.
UNIT II (9)
Elaboration - Domain Models - Finding conceptual classes and description classes –
Associations – Attributes – Domain model refinement – Finding conceptual class
hierarchies- Aggregation and Composition- UML activity diagrams and modeling

UNIT III (9)


System sequence diagrams - Relationship between sequence diagrams and use cases
Logical architecture and UML package diagram – Logical architecture refinement - UML
class diagrams - UML interaction diagrams
UNIT IV (9)
GRASP: Designing objects with responsibilities – Creator – Information expert – Low
Coupling –Controller – High Cohesion – Designing for visibility - Applying GoF design
patterns – adapter, singleton, factory and observer patterns.
UNIT V (9)
UML state diagrams and modeling - Operation contracts- Mapping design to code -UML
deployment and component diagrams

SVCE Page 1
Object Oriented Analysis and Design CS6502

UNIT I

Unit Syllabus: UML DIAGRAMS

Introduction to OOAD – Unified Process - UML diagrams – Use Case – Class Diagrams–
Interaction diagrams – State Diagrams – Activity Diagrams – Package, component and
Deployment Diagrams

1.INTRODUCTION TO OOAD:

OOAD: OBJECT ORIENTED ANALYSIS AND DESIGN

Analysis and Design:

Analysis emphasizes an investigation of the problem and requirements, rather than a solution.
For example, if a new computerized library information system is desired, how will it be
used?
"Analysis" is a broad term, best qualified, as in requirements analysis.

Design emphasizes a conceptual solution that fulfills the requirements, rather than its
implementation. For example, a description of a database schema and software objects.
Ultimately, designs can be implemented.

Object-Oriented Analysis and Design:

object-oriented analysis, there is an emphasis on finding and describing the objects—or


concepts—in the problem domain. For example, in the case of the library information system,
some of the concepts include Book, Library, and Patron.

object-oriented design, there is an emphasis on defining software objects and how they
collaborate to fulfil the requirements. For example, in the library system, a Book software
object may have a title attribute and a get Chapter method.

UML(Unified Modeling Language):

The Unified Modeling Language (UML) is a language for specifying, visualizing,


constructing, and documenting the artifacts of software systems, as well as for business
modeling and other non-software systems.

SVCE Page 2
Object Oriented Analysis and Design CS6502

Three Ways To Apply UML:

 UML as sketch: Informal and incomplete diagrams created to explore the difficult
parts of the problem/solution space.
 UML as blueprint: Relatively detailed design diagram used for either reverse
engineering or forward engineering (code generation).
 UML as programming language: Complete executable specification of a software
system in UML. Executable code will be automatically generated, but it is not
normally seen or modified by developers.

Three Perspectives To Apply UML:

 Conceptual perspectives: The diagrams are interpreted as describing things in a


situation of the real world or domain of interest.
 Specification perspectives(Software):The diagrams describe software abstractions
or components with specifications and interfaces, but no commitment to a particular
implementation. For e.g. not specifically a class in c# or java.
 Implementation perspectives: The diagrams describes software implementation in a
particular technology(such as java).

Meaning Of Class In Different Perspectives:

 Conceptual Class: real world concept or thing.


 Software class: a class repreenting a specification or implementation perspectives of
a software component.
 Implementation class: a class implemented in a specific oo language such as java.

Classification:

Broadly classified as

 Structural
 Behavioral

Diagram Types:
 Use case Diagram
 Activity diagram
 Class Diagram
 Sequence Diagram
 Communication diagram
 Component Diagram
 Deployment diagram
 Package Diagram
 State Machine diagram
 Timing diagram

SVCE Page 3
Object Oriented Analysis and Design CS6502

 Profile Diagram
 Composite Structure
 Object diagram
 Interaction Overview

2.UP (Unified Process):

Unified Process has emerged as a popular software development process for building object-
oriented systems.

Rational Unified Process or RUP:


A detailed refinement of the Unified Process.

Benefits of UP: 1. The UP is an iterative process. Iterative development is a valuable


practice that influences how this book introduces OOA/D, and how it is best practiced.2. UP
practices provide an example structure to talk about how to do—and how to learn—OOA/D.

Iterative Development:

 Development is organized into a series of short, fixed-length (for example, four week)
mini-projects called iterations.

 The outcome of each is a tested, integrated, and executable system. Each iteration
includes its own requirements analysis, design, implementation, and testing activities.

 The iterative lifecycle is based on the successive enlargement and refinement of a


system through multiple iterations, with cyclic feedback and adaptation as core
drivers to converge upon a suitable system. The system grows incrementally over
time, iteration by iteration, and thus this approach is also known as iterative and
incremental development

SVCE Page 4
Object Oriented Analysis and Design CS6502

 The output of an iteration is not an experimental or throw-away prototype, and


iterative development is not prototyping. Rather, the output is a production-grade
subset of the final system.

Benefits of Iterative Development:

Benefits of iterative development include:


 Early rather than late mitigation of high risks (technical, requirements,objectives,
usability, and so forth).
 Early visible progress.
 Early feedback, user engagement, and adaptation, leading to a refined system that
more closely meets the real needs of the stakeholders
 Managed complexity; the team is not overwhelmed by "analysis paralysis" or very
long and complex steps

Iteration Length and Time boxing:

The UP (and experienced iterative developers) recommends an iteration length between two
and six weeks. Small steps, rapid feedback, and adaptation are central ideas in iterative
development iterations are timeboxed, or fixed in length.

For example, if the next iteration is chosen to be four weeks long, then the partial system
should be integrated, tested, and stabilized by the scheduled date—date slippage is
discouraged.

SVCE Page 5
Object Oriented Analysis and Design CS6502

It will be difficult to meet the deadline, the recommended response is to remove tasks or
requirements from the iteration, and include them in a future iteration.

UP Phases:

1. Inception— approximate vision, business case, scope, vague estimates.


2. Elaboration—refined vision, iterative implementation of the core architecture, resolution
of high risks, identification of most requirements and scope, more realistic estimates.
3. Construction—iterative implementation of the remaining lower risk and easier elements,
and preparation for deployment.
4. Transition—beta tests, deployment.

Iterations
Each phase has iterations, each having the purpose of producing a demonstrable piece of
software. The duration of iteration may vary from two weeks or less up to six months.

Inception
• The life-cycle objectives of the project are stated, so that the needs of every stakeholder are
considered. Scope and boundary conditions, acceptance criteria and some requirements are
established.

Inception - Entry criteria


• The expression of a need, which can take any of the following forms:

-how, financial assets)


-up

Inception – Activities

late the scope of the project.


Needs of every stakeholder, scope, boundary conditions and acceptance criteria established.

Define risk mitigation strategy, develop an initial project plan and identify known cost,
schedule, and profitability trade-offs.

Candidate architecture is picked from various potential architectures


Prepare the project environment.

Inception - Exit criteria

SVCE Page 6
Object Oriented Analysis and Design CS6502

ntaining at least a clear formulation of the product vision - the


core requirements - in terms of functionality, scope, performance, capacity, technology base.

of the resources required to complete the elaboration phase.

Elaboration

An analysis is done to determine the risks, stability of vision of what the product is to
become, stability of architecture and expenditure of resources

Elaboration - Entry criteria

required for the elaboration phase have been allocated.

Elaboration – Activities

Project plan is defined. The process, infrastructure and development environment are
described.

To provide a stable basis for the bulk of the design and implementation effort in the
construction phase.

Elaboration - Exit criteria

plan, a staffing plan, a phase plan showing the number and contents of the iteration , an
iteration plan, and a test plan

e
‘complete’.

Construction

The Construction phase is a manufacturing process. It emphasizes managing resources and


controlling operations to optimize costs, schedules and quality. This phase is broken into
several iterations.

Construction - Entry criteria

SVCE Page 7
Object Oriented Analysis and Design CS6502

iteration specific goals

Construction – Activities

Components required satisfying the use cases, scenarios, and other functionality for the
iteration are built. Unit and integration tests are done on Components.
process.

Satisfaction of the goal of iteration is determined.

Construction - Exit Criteria

est cases and results of the tests conducted on the products,

Objective measurable evaluation criteria for assessing the results of the next iteration(s).

Transition

The transition phase is the phase where the product is put in the hands of its end users. It
involves issues of marketing, packaging, installing, configuring, supporting the user-
community, making corrections, etc.

Transition - Entry criteria

iteration, and in particular a software product


sufficiently mature to be put into the hands of its users.

Transition – Activities

Fine tune the product based upon customer feedback


liver the final product to the end user
-user support material

Transition - Exit criteria

SVCE Page 8
Object Oriented Analysis and Design CS6502

“postmortem” analysis of the performance of the project relative to its original and revised
success criteria;

UP Disciplines:

Discipline is a set of activities (and related artifacts) in one subject area, such as the
activities within requirements analysis. Artifact is the general term for any work product:
code, Web graphics, database schema, text documents, diagrams, models, and so on.

Some of the disciplines:

 Business Modeling—When developing a single application, this includes domain


object modeling. When engaged in large-scale business analysis or business process
reengineering, this includes dynamic modeling of the busi ness processes across the
entire enterprise.
 Requirements—Requirements analysis for an application, such as writing use cases
and identifying non-functional requirements.
 Design—All aspects of design, including the overall architecture, objects, databases,
networking.

SVCE Page 9
Object Oriented Analysis and Design CS6502

Disciplines and Phases:

Agile UP

 Agile process implies a light and adaptive process, nimble in response to changing
needs.

Case study: (Next generation POS system)

point-of-sale(POS)

 A POS system is a computerized application used (in part) to record sales and handle
payments; it is typically used in a retail store. It includes hardware components such
as a computer and bar code scanner, and software to run the system. It interfaces to
various service applications, such as a third-party tax calculator and inventory control.

SVCE Page 10
Object Oriented Analysis and Design CS6502

These systems must be relatively fault-tolerant; that is, even if remote services are
temporarily unavailable (such as the inventory system), they must still be capable of
capturing sales and handling at least cash payments.
 A POS system increasingly must support multiple and varied client-side terminals and
interfaces.

Layers Involved In POS System

 User Interface—graphical interface; windows.


 Application Logic and Domain Objects—software objects representing domain
concepts (for example, a software class named Sale) that fulfil application
requirements.
 Technical Services—general purpose objects and subsystems that provide supporting
technical services, such as interfacing with a database or error logging. These services
are usually application-independent and reusable across several systems.

Inception:

 The purpose of the inception step is not to define all the requirements, or generate a
believable estimate or project plan.
 Inception phase should be relatively short for most projects, such as one or a few
weeks long.
 The intent of inception is to establish some initial common vision for the objectives of
the project, determine if it is feasible, and decide if it is worth some serious
investigation in elaboration.

SVCE Page 11
Object Oriented Analysis and Design CS6502

Artifacts May Start in Inception:

Requirements:
 Requirements are capabilities and conditions to which the system and more broadly,
the project must conform.

Types of Requirements:
 Functional—features, capabilities, security.
 Usability—human factors, help, documentation.
 Reliability—frequency of failure, recoverability, predictability.
 Performance—response times, throughput, accuracy, availability, resource usage.
 Supportability—adaptability, maintainability, internationalization, configurability.
 Implementation—resource limitations, languages and tools, hardware.

SVCE Page 12
Object Oriented Analysis and Design CS6502

 Interface—constraints imposed by interfacing with external systems.


 Operations—system management in its operational setting.
 Packaging
 Legal—licensing and so forth

3.USE-CASE MODEL

Use cases—stories of using a system—is an excellent technique to understand and describe


requirements.
The UP defines the Use-Case Model within the Requirements discipline.
Essentially, this is the set of all use cases; it is a model of the system's functionality and
environment.

Notations:

An actor is something with behavior, such as a person (identified by role), computer system,
or organization; for example, a cashier.

A scenario is a specific sequence of actions and interactions between actors and


the system under discussion; it is also called a use case instance. It is one particular
story of using a system, or one path through the use case; for example, the scenario of
successfully purchasing items with cash, or the scenario of failing to purchase items because
of a credit card transaction denial.

Informally then, a use case is a collection of related success and failure scenarios that
describe actors using a system to support a goal. For example, here is a casual format use
case that includes some alternate scenarios:

Handle Returns

Main Success Scenario: A customer arrives at a checkout with items to return. The cashier
uses the POS system to record each returned item ...
Alternate Scenarios:
If the credit authorization is reject, inform the customer and ask for an alternate payment
method.
If the item identifier is not found in the system, notify the Cashier and suggest manual entry
of the identifier code (perhaps it is corrupted).
If the system detects failure to communicate with the external tax calculator system, ...

 Use cases are text documents, not diagrams, and use-case modeling is primarily an act
of writing text, not drawing. However, the UML defines a use case diagram to
illustrate the names of use cases and actors, and their relationships.

SVCE Page 13
Object Oriented Analysis and Design CS6502

Use Case Types

Black-box use cases are the most common and recommended kind; they do not describe the
internal workings of the system, its components, or design. Rather, the system is described as
having responsibilities, which is a common unifying metaphorical theme in object-oriented
thinking—software elements have responsibilities and collaborate with other elements that
have responsibilities it is possible to specify what the system must do (the functional
requirements) without deciding how it will do it (the design).

Formality Types

 brief—terse one-paragraph summary, usually of the main success scenario. The prior
Process Sale example was brief.
 casual—informal paragraph format. Multiple paragraphs that cover various scenarios.
The prior Handle Returns example was casual.
 fully dressed—the most elaborate. All steps and variations are written in detail, and
there are supporting sections, such as preconditions and success guarantees.

Fully Dressed Example: Process Sale


 Fully dressed use cases show more detail and are structured; they are useful in
order to obtain a deep understanding of the goals, tasks, and requirements.

Use Case UC1: Process Sale

Primary Actor: Cashier

Stakeholders and Interests:


- Cashier: Wants accurate, fast entry, and no payment errors, as cash drawer shortages are
deducted from his/her salary.
- Salesperson: Wants sales commissions updated.
- Customer: Wants purchase and fast service with minimal effort. Wants proof of purchase to
support returns.
- Company: Wants to accurately record transactions and satisfy customer interests.

SVCE Page 14
Object Oriented Analysis and Design CS6502

Wants to ensure that Payment Authorization Service payment receivables are recorded.
Wants some fault tolerance to allow sales capture even if server components (e.g., remote
credit validation) are unavailable. Wants automatic and fast update of accounting and
inventory.
- Government Tax Agencies: Want to collect tax from every sale. May be multiple agencies,
such as national, state, and county.
- Payment Authorization Service: Wants to receive digital authorization requests in the
correct format and protocol. Wants to accurately account for their payables to the
store.

Preconditions: Cashier is identified and authenticated.

Success Guarantee (Postconditions): Sale is saved. Tax is correctly calculated.


Accounting and Inventory are updated. Commissions recorded. Receipt is generated.
Payment authorization approvals are recorded.

Main Success Scenario (or Basic Flow):


1. Customer arrives at POS checkout with goods and/or services to purchase.
2. Cashier starts a new sale.
3. Cashier enters item identifier.
4. System records sale line item and presents item description, price, and running total.
Price calculated from a set of price rules.
Cashier repeats steps 3-4 until indicates ............

The Two-Column Variation:


The two-column or conversational format, which emphasizes the fact that there is an
interaction going on between the actors and the system.

SVCE Page 15
Object Oriented Analysis and Design CS6502

Preconditions state what must always be true before beginning a scenario in the use case.
Preconditions are not tested within the use case; rather, they are conditions that are assumed
to be true. Typically, a precondition implies a scenario of another use case that has
successfully completed, such as logging in, or the more general "cashier is identified and
authenticated."

Success guarantees (or postconditions) state what must be true on successful completion of
the use case.either the main success scenario or some alternate path. The guarantee should
meet the needs of all stakeholders.

Preconditions: Cashier is identified and authenticated.

Success Guarantee (Postconditions): Sale is saved. Tax is correctly calculated. Accounting


and Inventory are updated. Commissions recorded. Receipt is generated.
USE CASE
GUIDELINES:
 essential UI free style
 Terse use cases
 Black box use cases
 Actor and Actor goal perspective
 How to find use cases
– Choose system boundary
– Find primary actors
– Identify goals
– Define use cases that satisfy the goal

Elementary business processes:

SVCE Page 16
Object Oriented Analysis and Design CS6502

 EBP(elementary business processes) is a term from the business process engineering


field,defined as:
 A task performed by one person in one place at one time, in response to a business
event, which adds measurable business value and leaves the data in a consistent state.
e.g., Approve Credit or Price Order.

RELATING USE CASES:

Use cases can be related to each other. For example, a subfunction use case such as Handle
Credit Payment may be part of several regular use cases, such as Process Sale and Process
Rental. Organizing use cases into relationships has no impact on the behavior or requirements of
the system. Rather, it is simply an organization mechanism to (ideally) improve communication
and comprehension of the use cases, reduce duplication of text, and improve management of the
use case documents.

3 types:
The include Relationship
The extend Relationship
The generalize Relationship

The include Relationship:


It is common to have some partial behavior that is common across several use cases. For
example, the description of paying by credit occurs in several use cases, including Process
Sale, Process Rental, Contribute to Lay-away Plan.
This is simply refactoring and linking text to avoid duplication.

For example: UC1:


Process Sale
Main Success Scenario:
1 . Customer arrives at a POS checkout with goods and/or services to purchase.
7. Customer pays and System handles payment.
Extensions:
7b. Paying by credit: Include Handle Credit Payment. 7c. Paying by check:
Include Handle Check Pavment.

UC7: Process Rental


Extensions:
6b. Paying by credit: Include Handle Credit Payment.
UC12: Handle Credit Payment
Level: Subfunction Main Success Scenario:
1. Customer enters their credit account information.
2. System sends payment authorization request to an external Payment Authorization

Guideline of when to use the include relationship:

SVCE Page 17
Object Oriented Analysis and Design CS6502

Use include when you are repeating yourself in two or more separate use cases and you want
to avoid repetition. Another motivation is simply to decompose an overwhelmingly long use
case into subunits to improve comprehension.

Terminology: Concrete, Abstract, Base, and Addition UseCases

A concrete use case is initiated by an actor and performs the entire behaviour desired by the
actor . These are the elementary business process use cases. For example, Process Sale is a
concrete use case.
Abstract use case is never instantiated by itself; it is a subfunction use case that is part of
another use case. Handle Credit Payment is abstract; it doesn't stand on its own, but is always
part of another story, such as Process Sale.

A use case that includes another use case, or that is extended or specialized by
another use case is called a base use case. Process Sale is a base use case with
respect to the included Handle Credit Payment subfunction use case.

On the other hand, the use case that is an inclusion, extension, or specialization is
called an addition use case. Handle Credit Payment is the addition use case in
the include relationship to Process Sale.

Addition use cases are usually abstract.

Base use cases are usually concrete.

The Extend relationship:

– a dotted line labeled <<extend>> with an arrow toward the base case.
– The extending use case may add behavior to the base use case. The base class
declares “extension points”.
<<extend>>

4.UMLDIAGRAMS - CLASS DIAGRAMS

ELABORATION - DOMAIN MODEL

SVCE Page 18
Object Oriented Analysis and Design CS6502

• An idea, thing or object

• Considered in terms of
– Symbol
– Intension
– Extension

HOW TO CREATE DOMAIN MODEL

• Find Conceptual classes


• Draw them as classes in class diagram
• Add associations and attributes

HOW TO FIND CONCEPTUAL CLASSES

• Identify noun phrases


• Use category list
SVCE Page 19
Object Oriented Analysis and Design CS6502

• Reuse/modify existing models


CONCEPTUALCLASS

ASSOCIATIONS

• Relationship between classes


• Meaningful and interesting connection

ASSOCIATIONS
DEFINITION

• In UML, associations are defined as semantic relation between two or more classifiers
that involve connections among their instances

ASSOCIATION
UML NOTATION

• Denoted using a line between classes


• Capitalized association name
• Multiplicity-numerical relationship between instances of classes
• Bidirectional
• Classname-verbphrase-classname format

ASSOCIATION
EXAMPLE

SVCE Page 20
Object Oriented Analysis and Design CS6502

ASSOCIATION

• Common legal format


– Records-current
– RecordsCurrent
• End of association-Role
• Role optionally has
– Multiplicity
– Name

ASSOCIATION
MULTIPLICITY

• Multiplicity
– How many instances of class A can be associated with one instance of class B
– Context dependent

ASSOCIATION
MULTIPLICITY

SVCE Page 21
Object Oriented Analysis and Design CS6502

ASSOCIATION
MULTIPLE ASSOCIATION

ATTRIBUTES

• Logical data value of an object


• Shown in second compartment of a class box
• Required when need to be remembered
– Ex: cashier needs ID
– Sale needs a dateTime attribute
• Syntax
– Visibility name : type multiplicity=default{property string}

ATTRIBUTES
EXAMPLE

SVCE Page 22
Object Oriented Analysis and Design CS6502

ATTRIBUTE
DERIVED ATTRIBUTE
• Derived attribute denoted using / symbol before attribute name

Defining Conceptual Superclasses and Subclasses


• Conceptual superclass
– More general or encompassing than a subclass definition

Generalization and Class Sets

Payment
CheckPaym
CashPaymen CreditPay ent
t ment
SVCE Page 23
Object Oriented Analysis and Design CS6502

• Conceptual subclasses and superclasses are related in terms of set membership


• All members of a conceptual subclass set are members of their superclass set
• Eg., all instances of credit payment are also members of the set Payment
• Conceptual subclasses and superclasses are related in terms of set membership
• All members of a conceptual subclass set are members of their superclass set
• Eg., all instances of credit payment are also members of the set Payment

Conceptual subclass definition conformance

Payment
Pays-for Sale
amount : Money 1 1

Cash Credit Check


Payment Payment Payment

• When a class hierarchy is created, statements about superclasses that apply to


subclasses are made.
• Eg, Payments have an amount and are associated with a Sale
• All Payment subclasses must conform to having an amount and paying for a Sale.

GENERALIZATION
GUIDELINE
• 100% rule – definition conformance
– 100% of the conceptual Superclass’s definition should be applicable to the
subclass.
– The subclass must conform to 100% of the Superclass’s:
• attributes
• associations

GENERALIZATION
GUIDELINE

• Is-a rule –set membership conformance


– All members of a subclass set must be members of their superclass set
– Eg, Credit Payment is a kind of Payment
– In natural language, Subclass is a Superclass

When to define a Conceptual subclass


• Eg, Customer may be correctly partitioned into MaleCustomer and FemaleCustomer.

SVCE Page 24
Object Oriented Analysis and Design CS6502

• Correct subclasses, but not useful

CONCEPTUALCLASSHIERARCHY

ABSTRACT CLASS

• Abstract conceptual class


– If every member of a class C must also be a member of a subclass C is called
an abstract conceptual class

AGGREGATION AND COMPOSITION

• Composition
– Whole-part aggregation
– Strongly coupled
– Also known as composite aggregation
• Aggregation
– Whole-part relationship
– Loosely coupled

5.INTERACTION DIAGRAMS

 Interaction Diagrams are models that describe how a group of objects collaborate in
some behaviour
 Interaction Diagram model the behaviour of use cases by describing the way,groups
of objects interact to complete the task

SVCE Page 25
Object Oriented Analysis and Design CS6502

 Two types of Interaction diagram


1. Sequence diagram
2. Communication diagram

1. Sequence Diagram

A sequence diagram is a kind of interaction diagram that shows how processes


operate with one another and in what order

Communication Diagram

Communication Diagram is an interaction diagram which shows object interactions in


a graph or network format.Objects can be placed anywhere on the diagram

Strength and Weakness of sequence and communication Diagram


 Sequence Diagram
 Strengths

SVCE Page 26
Object Oriented Analysis and Design CS6502

1. Clearly shows sequence or time ordering of messages


2. It also possesses large set of detailed notations
 Weaknesses
1. Forced to extend to the right when adding new objects
2. Consumes horizontal space
• Communication Diagram
 Strengths
1. Space Economical
2. Flexibility to add new objects in two objects
 Weaknesses
1. More difficult to see sequence of messages
2. Fewer notation options

Common Notations in UML Interaction Diagram

1. Lifeline Box
2. Message Expression
3. Singleton Objects

Basic Sequence Diagram Notations


1. Lifeline Boxes and Lifelines
2. Messages
3. Focus of control and Execution specification bar
4. Reply or returns
5. Message to “self” or “this”
6. Instance creation
7. Object lifelines and object destruction
8. Frames
9. Looping
10. Conditional Messages
11. Mutually Exclusive Conditional Messages
12. Iteration over a collection
13. Nesting of frames
14. Messages to classes to invoke static ( or class) methods
15. Polymorphic Messages and cases
Asynchronous and Synchronous calls
Basic Communication Diagram Notations
1. Links
2. Messages
3. Message to “self” or “this”
4. Creation of instances
5. Message number sequencing
6. Conditional messages
7. Mutually exclusive conditional paths

SVCE Page 27
Object Oriented Analysis and Design CS6502

8. Iteration or Looping
9. Iteration over a collection
10. Messages to a classes to invoke static(class) methods
11. Polymorphic messages and cases
12. Asynchronous and synchronous calls

6.UML STATE DIAGRAM

 It is a type of diagram used to describe the behavior of systems.State diagrams require


that the system described is composed of a finite number of states
 State diagrams are used to give an abstract description of the behaviour of a
system.This behaviour is analyzed and represented in series of events,that could occur
in one or more possible states
 Each diagram usually represents objects of a single class and tracks different states of
its objects through the system

INTRODUCTION

 Shows dynamic views


 UML includes notation to illustrate the events and states of things, transitions, use
cases, people and so forth
 UML state machine diagram illustrates the interesting events and states of an object
and behavior of an object in reaction to an event
 Transitions are shown as arrows, labeled with their event
 States are shown in rounded rectangles

Notations in UML state diagram

1. Solid circle -> shows that starting point of the flow.Also


called as “Pseudo state”
2. Rounded rectangle -> represents the state of object at
an instant of time
3. Event/Action
Arrow labeled with their events -> indicating the object to transition
from one state to the other
4. Bull’s eye -> indicates the end of the diagram

STATE DIAGRAM COMPONENTS

 Event- significant or noteworthy occurrence


 ie., It is a notable occurrence at a particular point in time
 State – It is the condition of an object at a particular moment
 ie., time between events.state defines the behaviour of an object
 Transition –relationship between two states that indicates that when an event
occurs,the object moves from the previous state to the next/subsequent state
SVCE Page 28
Object Oriented Analysis and Design CS6502

STATE DIAGRAM COMPONENTS

 Events - start game (to reach Initialised state),move (to reach Moving state)
 State - Initialized,Moving
 Transition - When the event moves occurs,transition takes place from the Initialized
to Moving state

STATE DIAGRAM

 OBJECT TYPES

1. State independent objects


 Objects are state independent,if their behaviour does not depend on their particular
current state ie., If an object receives a message and the corresponding method always
does the same thing
2. State dependent objects
 An object is said to be state dependent,if the object react differently to events
depending on their state or mode
Guideline:
 consider state machine diagram for state dependent objects with complex
behavior

MODELING STATE DEPENDENT OBJECTS


2 ways :

1.To model the behavior of complex reactive object in response of events


2.To model the legal sequence of operations,protocols or language specifications

 A formal grammar for a context-free language is a kind of state machine

COMPLEX REACTIVE OBJECTS

1. Physical devices controlled by software


 Reactions depends upon their current mode
Ex: phone, car, microwave oven,air condition,etc
2. Transactions and related business objects
 Transactions - Ticket Reservation,Payroll calculation,etc.
 Business Objects - Reservation,Payment,Salary,etc.
3. Role mutators
 Objects that change their role
Ex: A Person changing roles from being a student to a staff

SVCE Page 29
Object Oriented Analysis and Design CS6502

2.PROTOCOLS AND LEGAL SEQUENCES

1. Communication protocols
2. UI page/window flow of navigation
3. UI flow controllers or sessions
4. Use case system operations
5. Individual UI window event handling

More UML State Machine Diagram Notation


1. Transition Action
 It can cause an action to fire
 It is performed when performing a certain transition
2. Guard/Conditional Guard
 It is a Boolean condition that is evaluated when a transition initiates
 Transition occur when the Guard condition is TRUE
3. Nested states
 States that contain other states (substates) known as Nested states.Substate inherits the
transitions of its Superstate
 Substates graphically shown by nesting them in a superstate box.

TRANSITION ACTION AND GUARDS

NESTED STATES

SVCE Page 30
Object Oriented Analysis and Design CS6502

7.UML ACTIVITY DIAGRAM

 It used to provide a view of flows and what is going on inside a use-case or among
several classes
 Shows parallel and sequential activities in a process
 Used in business processes, work flows, data flows, complex algorithm
 UML activity diagrams are the object oriented equivalent of flow charts and data flow
diagrams from structured development

UML ACTIVITY DIAGRAM AND MODELING

 UML Activity diagram


 Shows parallel and sequential activities in a process
 Used in
 Business Process Modeling
 work flows
 data flows
 complex algorithm
UML ACTIVITY DIAGRAM AND MODELING
 Activity diagram Notation
 Action
 Partition
 Fork
SVCE Page 31
Object Oriented Analysis and Design CS6502

 Join
 Object node
 Types of flow/edge
1)Object flow -> flow between the partitions
2)Control flow ->flow in the same partition

UML ACTIVITY DIAGRAM AND MODELING


Activity diagram Notation
Initial Node
Final Node
Action
Flow/edge
(Object flow,
Control flow)
Fork
Join
Decision
Merge
Partition
Sub-activity indicator
Note

SVCE Page 32
Object Oriented Analysis and Design CS6502

How to apply activity diagram

 Business process modeling


 Uses activity diagram to understand their current complex business process by
visualizing them.

 Data flow modeling


 Data flow diagram -1970’s
 It is a graphical representation of the flow of data through an information
system
 To visualize the major steps and data involved in software system processes.
 Used in documentation and discovery
 UML does not include DFD notation.

SVCE Page 33
Object Oriented Analysis and Design CS6502

 Rake symbol-Expanding an activity in another activity diagram

8.PACKAGE DIAGRAM

 UML Package Diagram used to represent the logical architecture of a system -


the layers, sub classes, packages, etc
Ex: UI layer as UI Package
 It simplify complex class diagrams, it can group classes into Packages.A package
is a collection of logically related UML elements. Packages are depicted as file
folders and can be used on any of the UML diagrams.
 A way to group elements
 Dependency between packages shown using UML dependency line
 Represents name space
 Useful in reverse engineering

SVCE Page 34
Object Oriented Analysis and Design CS6502

Applying UML-Package Diagrams

 UML Package Diagram is a way of grouping elements such as classes,other


packages,use cases,etc
 Package name can be placed on the tab if the package shows inner members or on the
main folder.
 UML dependency line with the arrow pointing towards the dependency-on package
can be used to show coupling
 UML package diagram can also make use of namespace
 UML providees an alternatie notation to llustrate outer and inner nested
packages,instead of drawing outer package box around inner packages

GUIDELINES
 Design with layers
 Model view separation principle
 Collaboration and coupling from higher to lower layers
 High cohesion

SVCE Page 35
Object Oriented Analysis and Design CS6502

Layer
 A Layer is a coarse grained of classes,packages or subsystems
 Higher Layers(UI Layer) call upon services of Lower Layers
 Layers in Object Oriented System

1. User Interface – Graphical User Interface


2. Application Logic and Domain Objects – s/w objects representing domain concepts such as
software class authentication, transaction that satisfies the application requirements such as
validating the bank client
3. Technical Services – General purpose objects and subsystems that provide technical
services such as interfacing with a database,error logging,etc.These services are application
independent and reusable

9.UML COMPONENT DIAGRAM

Component Diagram shows how the physical components of a system are organized.It helps
to model the physical aspect of an object oriented software system

It illustrates the architectures of the software components and the dependencies between
them.

 Represents a modular part of a system


 Encapsulates contents
 Replaceable
 Behavior in terms of interfaces
 Design level perspective
 Ex: home entertainment system

COMPONENTDIAGRAMNOTATION
 Components are shown as rectangles with two tabs at the upper left
 Dashed arrows indicate dependencies
 Circle and solid line indicates an interface to the component

SVCE Page 36
Object Oriented Analysis and Design CS6502

COMPONENT ELEMENTS
 A component can have
 Interfaces
 Usage dependencies
 Ports
 Connectors

Component
 A Component is a physical building block of a system that encapsulates its contents
and whose manifestation is replaceable within its enviornment
 A component defines its behaviour in terms of provided and required interfaces

INTERFACE
 An interface
 It describes a group of operations used or created by components
 Provides only the operations but not the implementation
 Implementation is normally provided by a class/ component
 In complex systems, the physical implementation is provided by a group of
classes rather than a single class
 May be shown using a rectangle symbol with a keyword <<interface>> preceding the
name
 For displaying the full signature, the interface rectangle can be expanded to show
details
 Can be
 Provided
 Required
INTERFACE
PROVIDED INTERFACE

SVCE Page 37
Object Oriented Analysis and Design CS6502

 Characterize services that the component offers to its environment


 Is modeled using a ball, labelled with the name, attached by a solid line to the
component

INTERFACE
REQUIRED INTERFACE
 Characterize services that the component expects from its environment
 Is modeled using a socket, labelled with the name, attached by a solid line to the
component

DEPENDENCIES
Components can be connected by usage dependencies
 Usage Dependency
 A relationship which one element requires another element for its full
implementation
 A dependency in which the client requires the presence of the supplier
 Is shown as dashed arrow with a <<use>> keyword
 The arrowhead point from the dependent component to the one of which it is
dependent
PORT
 Specifies a distinct interaction point
 Between that component and its environment
 Between that component and its internal parts

 Is shown as a small square symbol


 name is placed near the square symbol
 Is associated with the interfaces that specify the nature of the interactions that may
occur over a port
 Supports unidirectional communication or bi-directional communication

SVCE Page 38
Object Oriented Analysis and Design CS6502

 multiple interfaces associated with a port, listed with the interface icon, separated by a
commas

EXTERNAL VIEW

 A component have an external view and an internal view


 An external view of a component is by means of interface symbols sticking out of the
component box
 An external view (or black box view) shows publicly visible properties and operations
 The interface can be listed in the compartment of a component box

INTERNAL VIEW

 An internal, or white box view of a component is where the realizing


classes/components are nested within the component shape

 Realization is a relationship between two set of model elements

 One represents a specification

 The other represent an implementation of the latter

SVCE Page 39
Object Oriented Analysis and Design CS6502

COMPONENT EXAMPLE – LINKING

10.UML DEPLOYMENT DIAGRAM

SVCE Page 40
Object Oriented Analysis and Design CS6502

• A Deployment Diagram depicts a static view of the run-time configuration of


hardware nodes and the software components that run on those nodes.

• Deployment diagrams show the hardware of the system, the software that is installed
on that hardware, and the middleware used to connect the disparate machines to one
another.

• Deployment diagram
• Shows assignment of concrete software architects(executable files) to
computational nodes
• It shows,
• Deployment of software elements to the physical architecture
• Communication between the physical elements
• Basic element – node

Elements of DEPLOYMENT DIAGRAM

1.Node

 element that provides the execution environment for the components of a system

 Two types of Nodes

i. Device Node - A physical(digital electronic)computing resource with processing and


memory services to execute software such as a typical computer or a mobile phone

ii. Execution Environment Node (EEN) - This is a software computing resource that runs
within an outer node(such as computer)and which itself provides a service to host and
execute other executable software elements Eg., OS,VM,DB Engine,Web Browser,workflow
engine,servlet container or EJB container

2. Connection

 This is to define the interconnection between the nodes

Symbol:

Solid Line

Dashed Arrow

SVCE Page 41
Object Oriented Analysis and Design CS6502

SVCE Page 42
Object Oriented Analysis and Design CS6502

Unit 2 Design Patterns

Unit Syllabus : DESIGN PATTERNS

GRASP: Designing objects with responsibilities – Creator – Information expert – Low


Coupling – High Cohesion – Controller - Design Patterns – creational - factory method -
structural – Bridge – Adapter - behavioral – Strategy – observer

1.GRASP-General Responsibilty Assignment Software Patterns


Thinking about the design of software objects and also larger-scale components is
in terms of responsibilities , roles , and collaborations . This approach is called
responsibility-driven design or RDD

Responsibilities are of the following two types: doing and knowing .

Doing responsibilities of an object include:

doing something itself, such as creating an object or doing a calculation


initiating action in other objects
controlling and coordinating activities in other objects
Knowing responsibilities of an object include:

knowing about private encapsulated data


knowing about related objects
knowing about things it can derive or calculate
Responsibilities are assigned to classes of objects during object design.
For example, "a Sale is responsible for creating SalesLineItems " (a doing), or "a Sale is
responsible for knowing its total" (a knowing).

GRASP: A Learning Aid for OO Design with Responsibilities

What's the Connection Between Responsibilities,GRASP, and UML Diagrams?

Sale objects have been given a responsibility to create Payments , which is invoked
with a makePayment message and handled with a corresponding makePayment
method.

SVCE Page 43
Object Oriented Analysis and Design CS6502

Further, the fulfillment of this responsibility requires collaboration to create the


payment object and invoke its constructor.

Therefore, when we draw a UML interaction diagram, we are deciding on responsibility


assignments.
In OO design, a pattern is a named description of a problem and solution that can be applied
to new contexts; ideally, a pattern advises us on how to apply its solution in varying
circumstances.
Many patterns, given a specific category of problem, guide the assignment of responsibilities
to objects.
New pattern should be considered an oxymoron if it describes a new idea. The very term
pattern"
suggests a long-repeating thing

9 GRASP patterns

– Information Expert

– Creator

– Controller

– Low Coupling

– High Cohesion

– Polymorphism

SVCE Page 44
Object Oriented Analysis and Design CS6502

– Pure Fabrication.

– Indirection

Name: Creator
Problem: Who creates an A?
Solution: Assign class B the responsibility to create an instance of class A if one of
these is true

B "contains" or compositely aggregates A.


B records A.
B closely uses A.
B has the initializing data for A.

Example Problem

Who should create a SalesLineItem?

Sale

time

Contains

1..*
Product
Sales Description
LineItem * Described-by 1
description
quantity price
itemID

SVCE Page 45
Object Oriented Analysis and Design CS6502

So Sale class aggregates SalesLineItem objects so Sale class creates the SalesLineItem
objects.

Name: Information Expert


Problem: What is a basic principle by which to assign responsibilities to objects?
Solution: Assign a responsibility to the class that has the information needed to fulfill it.
A responsibility needs information of the object, an object's own state, the
world around an object, information the object can derive, and so forth to fulfil
it .

Example
Who should be responsible for knowing/getting the grand total of a sale?

Sale

time

Contains

1..*
Product
Sales Description
LineItem * Described-by 1
description
quantity price
itemID

SVCE Page 46
Object Oriented Analysis and Design CS6502

Sale

time
...
t = getTotal 1 *: st = getSubtotal lineItems[ i ] :
: Sale getTotal()
SalesLineItem

1.1: p := getPrice() SalesLineItem

quantity
:Product getSubtotal()
Description

Product
Description

description
price
itemID
New method getPrice()

Name: Controller
Problem: What first object beyond the UI layer receives and coordinates("controls")
a system operation?
Solution: Assign the responsibility to an object representing one of these choices

Represents the overall "system," a "root object," a device that the software is running within,
or a major subsystem.
ex: ATM machine,Phone
Represents a use case scenario within which the system operation occurs(a use case or
session controller )

SVCE Page 47
Object Oriented Analysis and Design CS6502

Ex:Process Sale controller or ProcessSale Handler

presses button

: Cashier

actionPerformed( actionEvent )

UI Layer :SaleJFrame

system operation message


enterItem(itemID, qty)

Which class of object should be responsible for receiving this


Domain system event message?
: ???
Layer
It is sometimes called the controller or coordinator. It does not
normally do the work, but delegates it to other objects.

The controller is a kind of "facade" onto the domain layer from


the interface layer.

presses button

Cashier

actionPerformed( actionEvent )

It is undesirable for an interface


layer object such as a window to get
UI Layer :SaleJFrame involved in deciding how to handle
domain processes.

Business logic is embedded in the


presentation layer, which is not useful.

1: makeLineItem(itemID, qty)
Domain Layer :Sale

SaleJFrame should not


send this message.

SVCE Page 48
Object Oriented Analysis and Design CS6502

CONTROLLER: BENEFITS
 Increased potential for reuse
 Plug & Play interfaces
 Allows us to verify that the system operations occur in a logical sequence. For
example: makePayment() is not called before endSale()

Name: High Cohesion


Problem: How to keep objects focused, understandable, and manageable, and as
a
Side effect, support Low Coupling?
Solution: Assign responsibilities so that cohesion remains high.

Cohesion is a measure of how strongly related the responsibilities of an element


(classes, subsystems) are.

Ex: Low cohesion:


Register is taking part of the responsibility for fulfilling “makePayment” operation
and many other unrelated responsibility ( 50 system operations all received by
Register).then it will become burden with tasks and become incohesive

: Register : Sale

makePayment()
create()
p : Payment

addPayment( p )

Delegate the payment creation responsibility to “Sale” to support high cohesion

: Register : Sale
SVCE Page 49
makePayment()
makePayment()
create() : Payment
Object Oriented Analysis and Design CS6502

Coupling is a measure of how strongly one element is connected to, has knowledge
of, or depends on other elements.
If there is coupling or dependency, then when the depended-upon element changes,
the dependant may be affected.
Common form of coupling from Class A to Class B are:

 Class A has a method which references an instance of Class B, or Class B


itself, by any means. These typically include a parameter or local variable of
type Class B, or the object returned from a message being an instance of Class
B.
 Class A is a direct or indirect subclass of Class B.
 Class B is an interface, and Class A implements that interface.

Name: Low Coupling


Problem: How to reduce the impact of change?
Solution: Assign responsibilities so that (unnecessary) coupling remains low.
Use
this principle to evaluate alternatives

makePayment() 1: create()
: Register p : Payment

2: addPayment(p)
:Sale

In the above figure Register is coupled to both Sale and Payment

makePayment() 1: makePayment()
SVCE : Register :Sale Page 50

1.1. create()

:Payment
Object Oriented Analysis and Design CS6502

Assuming that the Sale must eventually be coupled to knowledge of a Payment,


having Sale create the Payment does not increase coupling.

NB : Low Coupling and Creator may suggest different solutions.

2.Design Patterns

Purpose of patterns

• Creational patterns concern the process of object creation.

• Structural patterns deal with the composition of classes or objects.

• Behavioral patterns characterize the ways in which classes or objects interact and
distribute responsibility.

• Creational Patterns

• Creational design patterns abstract the instantiation process.

• They help make a system independent of how its objects are created, composed, and
represented.

• A class creational pattern uses inheritance to vary the class that's instantiated, whereas
an object creational pattern will delegate instantiation to another object.

Recurring themes

• two recurring themes in these patterns.

• First, they all encapsulate knowledge about which concrete classes the system uses.

• Second, they hide how instances of these classes are created and put together.

Configuration

• Creational patterns gives a lot of flexibility in what gets created, who creates it, how it
gets created, and when.

SVCE Page 51
Object Oriented Analysis and Design CS6502

• They let you configure a system with "product" objects that vary widely in structure
and functionality.

Configuration can be static (that is, specified at compile-time) or dynamic (at run-time)

Example

• Building a maze for a computer game—to illustrate the implementation.

• The maze and the game will vary slightly from pattern to pattern.

• Sometimes the game will be to find your way out of a maze; in that case the player
will probably only have a local view of the maze.

• Sometimes mazes contain problems to solve and dangers to overcome, and these
games may provide a map of the part of the maze that has been explored.

Ignored Details

Ignore many details of what can be in a maze and whether a maze game has a single or
multiple players.

Focused details

• How mazes get created.

• We define a maze as a set of rooms.

• A room knows its neighbors.

• Possible neighbors are another room, a wall, or a door to another room.

Classes for the example

• The classes Room, Door, and Wall define the components of the maze used.

• We define only the parts of these classes that are important for creating a maze.

• We'll ignore players, operations for displaying and wandering around in a maze, and
other important functionality that isn't relevant to building the maze.

Relationship between classes

SVCE Page 52
Object Oriented Analysis and Design CS6502

Room class

• Each room has four sides.

• Use an enumeration Direction in C++ implementations to specify the north, south,


east, and west sides of a room:

• enum Direction {North, South, East, West};

Class MapSite

• The class MapSite is the common abstract class for all the components of a maze.

• MapSite defines only one operation, Enter. Its meaning depends on what you're
entering.

• If you enter a room, then your location changes. If you try to enter a door, and If the
door is open, you go into the next room.

class MapSite {

public:

virtual void Enter() = 0;

};

• Room is the concrete subclass of MapSite that defines the key relationships between
components in the maze.

SVCE Page 53
Object Oriented Analysis and Design CS6502

• It maintains references to other MapSite objects and stores a room number. The
number will identify rooms in the maze.

class Room : public MapSite {

public:

Room(int roomNo);

MapSite* GetSide(Direction) const;

void SetSide(Direction, MapSite*);

virtual void Enter();

private:

MapSite* _sides[4];

int _roomNumber;

};

The following classes represent the wall or door that occurs on each side of a room.

class Wall : public MapSite {

public:

Wall();

virtual void Enter();

};

class Door : public MapSite {

public:

Door(Room* = 0, Room* = 0);

virtual void Enter();

Room * OtherSideFrom(Room*);

private:

Room* _room1;

SVCE Page 54
Object Oriented Analysis and Design CS6502

Room* _room2;

bool _isOpen;

};

A Maze class represents a collection of rooms. Maze can also find a particular room given a
room number using its RoomNo operation.

class Maze {

public:

Maze();

void AddRoom(Room*);

Room* RoomNo(int) const;

private:

// ...

};

RoomNo could do a look-up using a linear search, a hash table, or even a simple array.

• Another class is MazeGame, which creates the maze.

• One way to create a maze is with a series of operations that add components to a
maze and then interconnect them.

• For eg, the following member function will create a maze consisting of two rooms
with a door between them

Maze* MazeGame::CreateMaze () {

Maze* aMaze = new Maze;

Room* r1 = new Room(1);

Room* r2 = new Room(2);

Door* theDoor = new Door(r1, r2);

aMaze->AddRoom(r1);

aMaze->AddRoom(r2);

SVCE Page 55
Object Oriented Analysis and Design CS6502

r1->SetSide(North, new Wall);

r1->SetSide(East, theDoor);

r1->SetSide(South, new Wall);

r1->SetSide(West, new Wall);

r2->SetSide(North, new Wall);

r2->SetSide(East, new Wall);

r2->SetSide(South, new Wall);

r2->SetSide(West, theDoor);

return aMaze;

• This is for creating a maze with two rooms.

Layout

• Changing the layout means changing this member function, either by overriding it—
which means reimplementing the whole thing—or by changing parts of it—which is
error-prone and doesn't promote reuse.

• Inflexible.

Use of creational

• The creational patterns show how to make this design more flexible, not necessarily
smaller.

• They will make it easy to change the classes that define the components of a maze.

Creational pattern

• Suppose you wanted to reuse an existing maze layout for a new game containing (of
all things) enchanted mazes.

• The enchanted maze game has new kinds of components, like DoorNeedingSpell, a
door that can be locked and opened subsequently only with a spell; and
EnchantedRoom, a room that can have unconventional items in it, like magic keys or
spells.

How to change CreateMaze easily so that it creates mazes with these new classes of objects
SVCE Page 56
Object Oriented Analysis and Design CS6502

Barrier

• The biggest barrier to change lies in hard-coding the classes that get instantiated.

• The creational patterns provide different ways to remove explicit references to


concrete classes from code that needs to instantiate them.

Patterns

• If CreateMaze calls virtual functions instead of constructor calls to create the rooms,
walls, and doors it requires, then you can change the classes that get instantiated by
making a subclass of MazeGame and redefining those virtual functions. This
approach is an example of the Factory Method pattern.

• If CreateMaze is passed an object as a parameter to use to create rooms, walls, and


doors, then you can change the classes of rooms, walls, and doors by passing a
different parameter. This is an example of the Abstract Factory pattern.

Patterns

• If CreateMaze is passed an object that can create a new maze in its entirety using
operations for adding rooms, doors, and walls to the maze it builds, then you can use
inheritance to change parts of the maze or the way the maze is built. This is an
example of the Builder pattern.

• If CreateMaze is parameterized by various prototypical room, door, and wall objects,


which it then copies and adds to the maze, then you can change the maze's
composition by replacing these prototypical objects with different ones. This is an
example of the Prototype pattern.

Pattern

• The remaining creational pattern, Singleton, can ensure there's only one maze per
game and that all game objects have ready access to it—without resorting to global
variables or functions.

• Singleton also makes it easy to extend or replace the maze without touching existing
code.

Factory Method
SVCE Page 57
Object Oriented Analysis and Design CS6502

• Define an interface for creating an object, but let subclasses decide which class to
instantiate.

• Factory Method lets a class defer instantiation to subclasses.

• AKA Virtual Constructor

Motivation

• Frameworks use abstract classes to define and maintain relationships between objects.

• A framework is often responsible for creating these objects as well.

• Consider a framework for applications that can present multiple documents to the
user.

• Two key abstractions in this framework are the classes Application and Document.

• Both classes are abstract, and clients have to subclass them to realize their
application-specific implementations.

• To create a drawing application, for example, we define the classes


DrawingApplication and DrawingDocument.

• The Application class is responsible for managing Documents and will create them as
required—when the user selects Open or New from a menu, for example.

• Because the particular Document subclass to instantiate is application-specific, the


Application class can't predict the subclass of Document to instantiate—the
Application class only knows when a new document should be created, not what kind
of Document to create.

This creates a dilemma: The framework must instantiate classes, but it only knows about
abstract classes, which it cannot instantiate

Solution

• The Factory Method pattern offers a solution.

• It encapsulates the knowledge of which Document subclass to create and moves this
knowledge out of the framework.

Factory Method

SVCE Page 58
Object Oriented Analysis and Design CS6502

• Application subclasses redefine an abstract CreateDocument operation on Application


to return the appropriate Document subclass.

• Once an Application subclass is instantiated, it can then instantiate application-


specific documents without knowing their class.

• CreateDocument is a factory method because it's responsible for "manufacturing" an


object.

Applicability

Use the Factory Method pattern when

• a class can't anticipate the class of objects it must create.

• a class wants its subclasses to specify the objects it creates.

classes delegate responsibility to one of several helper subclasses, and you want to localize
the knowledge of which helper subclass is the delegate

Structure

SVCE Page 59
Object Oriented Analysis and Design CS6502

Participants

• Product (Document)

– defines the interface of objects the factory method creates.

• ConcreteProduct (MyDocument)

– implements the Product interface.

• Creator (Application)

– m declares the factory method, which returns an object of type Product.


Creator may also define a default implementation of the factory method that
returns a default ConcreteProduct object.

– may call the factory method to create a Product object.

• ConcreteCreator (MyApplication)

– m overrides the factory method to return an instance of a ConcreteProduct.

Collaborations

Creator relies on its subclasses to define the factory method so that it


returns an instance of the appropriate ConcreteProduct.

Consequences

• Factory methods eliminate the need to bind application-specific classes into your
code.

SVCE Page 60
Object Oriented Analysis and Design CS6502

• The code only deals with the Product interface; therefore it can work with any user-
defined ConcreteProduct classes.

• Subclassing is fine when the client has to subclass the Creator class.

• Here are two additional consequences of the Factory Method pattern:

• Provides hooks for subclasses

• Connects parallel class hierarchies

Summary

• Factory method defines the connection between the two class hierarchies.

• It localizes knowledge of which classes belong together.

Implementation

• Consider the issues when applying the Factory Method pattern:

• Two major varieties: The two main variations of the Factory Method pattern are

(1) the case when the Creator class is an abstract class and does not provide an
implementation for the factory method it declares,

(2) the case when the Creator is a concrete class and provides a default implementation for
the factory method.

Issues

• Parameterized factory methods: The factory method creates multiple kinds of


products.

SVCE Page 61
Object Oriented Analysis and Design CS6502

• The factory method takes a parameter that identifies the kind of object to create.

• All objects the factory method creates will share the Product interface

• A parameterized factory method has the following general form, where


MyProduct and YourProduct are subclasses of Product:

class Creator {

public:

virtual Product* Create(ProductId);

};

Product* Creator::Create (ProductId id) {

if (id == MINE) return new MyProduct;

if (id == YOURS) return new YourProduct;

// repeat for remaining products...

return 0;

• A subclass MyCreator could swap MyProduct and YourProduct and support a


new TheirProduct subclass:

Product* MyCreator::Create (ProductId id) {

if (id == YOURS) return new MyProduct;

if (id == MINE) return new YourProduct;

// N.B.: switched YOURS and MINE

if (id == THEIRS) return new TheirProduct;

return Creator::Create(id); // called if all others fail

Parameterized factory methods

• call Create on the parent class.

SVCE Page 62
Object Oriented Analysis and Design CS6502

• That's because MyCreator::Create handles only YOURS, MINE, and THEIRS


differently than the parent class.

• It isn't interested in other classes.

• Hence MyCreator extends the kinds of products created, and it defers responsibility
for creating all but a few products to its parent.

Language-specific variants and issues

• A Smalltalk version of the Document example can define a documentClass method on


Application.

• The documentClass method returns the proper Document class for instantiating
documents.

• The implementation of documentClass in MyApplication returns the MyDocument


class. Thus in class Application we have

clientMethod

document := self documentClass new.

documentClass

self subclassResponsibiliIn class MyApplication we have

documentClass

^ MyDocument

which returns the class MyDocument to be instantiated to Application.

• An even more flexible approach akin to parameterized factory methods is to store the
class to be created as a class variable of Application.

• That way you don't have to subclass Application to vary the product.

• Factory methods in C++ are always virtual functions and are often pure virtual.

• Do not call factory methods in the Creator's Constructor —the factory method in the
ConcreteCreator won't be available yet.

• You can avoid this by being careful to access products solely through accessor
operations that create the product on demand.

SVCE Page 63
Object Oriented Analysis and Design CS6502

• Instead of creating the concrete product in the constructor, the constructor merely
initializes it to 0.

• The accessor returns the product. But first it checks to make sure the product exists,
and if it doesn't, the accessor creates it.

• This technique is sometimes called lazy initialization.

class Creator {

public:

Product* GetProduct();

protected:

virtual Product* CreateProduct();

private:

Product* _product;

};

Product* Creator::GetProduct () {

if (_product == 0) {

_product = CreateProduct();

return _product;

Using templates to avoid subclassing

• force you to subclass just to create the appropriate Product objects.

• Another way to get around this in C++ is to provide a template subclass of Creator
that's parameterized by the Product class

class Creator {

public:

virtual Product* CreateProduct() = 0;

};

SVCE Page 64
Object Oriented Analysis and Design CS6502

template <class TheProduct>

class StandardCreator: public Creator {

public:

virtual Product* CreateProduct();

};

template <class TheProduct>

Product* StandardCreator<TheProduct>::CreateProduct () {

return new TheProduct;

With this template, the client supplies just the product class—no subclassing of Creator is
required.

class MyProduct : public Product {

public:

MyProduct();

// ...

};

StandardCreator<MyProduct> myCreator;

Naming conventions

For example, the MacApp Macintosh application framework always declares the abstract
operation that defines the factory method as Class* DoMakeClass(), where Class is the
Product class.

Sample Code

First we'll define factory methods in MazeGame for creating the maze, room, wall, and
door objects:

class MazeGame {

public:

SVCE Page 65
Object Oriented Analysis and Design CS6502

Maze* CreateMaze();

// factory methods:

virtual Maze* MakeMaze() const

{ return new Maze; }

virtual Room* MakeRoom(int n) const

{ return new Room(n); }

virtual Wall* MakeWall() const

{ return new Wall; }

virtual Door* MakeDoor(Room* r1, Room* r2) const

{ return new Door(r1, r2); }

};

Maze* MazeGame::CreateMaze () {

Maze* aMaze = MakeMaze();

Room* r1 = MakeRoom(1);

Room* r2 = MakeRoom(2);

Door* theDoor = MakeDoor(r1, r2);

aMaze->AddRoom(r1);

aMaze->AddRoom(r2);

r1->SetSide(North, MakeWall());

r1->SetSide(East, theDoor);

r1->SetSide(South, MakeWall());

r1->SetSide(West, MakeWall());

r2->SetSide(North, MakeWall());

r2->SetSide(East, MakeWall());

r2->SetSide(South, MakeWall());

SVCE Page 66
Object Oriented Analysis and Design CS6502

r2->SetSide(West, theDoor);

return aMaze;

class BombedMazeGame : public MazeGame {

public:

BombedMazeGame();

virtual Wall* MakeWall() const

{ return new BombedWall; }

virtual Room* MakeRoom(int n) const

{ return new RoomWithABomb(n); }

};

class EnchantedMazeGame : public MazeGame {

public:

EnchantedMazeGame();

virtual Room* MakeRoom(int n) const

{ return new EnchantedRoom(n, CastSpell()); }

virtual Door* MakeDoor(Room* r1, Room* r2) const

{ return new DoorNeedingSpell(r1, r2); }

protected:

Spell* CastSpell() const;

};

STRUCTURAL PATTERNS

• are concerned with how classes and objects are composed to form larger structures.

• Structural class patterns use inheritance to compose interfaces or implementations.

SVCE Page 67
Object Oriented Analysis and Design CS6502

• As a simple example, consider how multiple inheritance mixes two or more classes
into one. The result is a class that combines the properties of its parent classes.

• This pattern is useful for making independently developed class libraries work
together.

• Another example is the class form of the Adapter pattern.

structural object patterns

• Structural object patterns describe ways to compose objects to realize new


functionality.

• The added flexibility of object composition comes from the ability to change the
composition at run-time, which is impossible with static class composition.

• Composite is an example of a structural object pattern.

Composite

• describes how to build a class hierarchy made up of classes for two kinds of objects:

– primitive and

– composite.

The composite objects let you compose primitive and other composite objects into arbitrarily
complex structures

Proxy

• proxy acts as a convenient surrogate or placeholder for another object.

• It can act as a local representative for an object in a remote address space.

• It can represent a large object that should be loaded on demand.

• It might protect access to a sensitive object.

• Proxies provide a level of indirection to specific properties of objects.

• They can restrict, enhance, or alter these properties.

Flyweight

• defines a structure for sharing objects.

• Objects are shared for at least two reasons:

SVCE Page 68
Object Oriented Analysis and Design CS6502

efficiency and consistency.

• Flyweight focuses on sharing for space efficiency.

• Applications that use lots of objects must pay careful attention to the cost of each
object.

Substantial savings can be had by sharing objects instead of replicating them

Flyweight

• But objects can be shared only if they don't define context –dependent state.

• Flyweight objects have no such state. Any additional information they need to
perform their task is passed to them when needed.

• With no context-dependent state, Flyweight objects may be shared freely.

Façade

• Façade shows how to make a single object represent an entire subsystem.

• A facade is a representative for a set of objects.

• The facade carries out its responsibilities by forwarding messages to the objects it
represents.

Bridge

The Bridge pattern separates an object's abstraction from its implementation so that you can
vary them independently.

Decorator

• Decorator describes how to add responsibilities to objects dynamically.

• Decorator is a structural pattern that composes objects recursively to allow an open-


ended number of additional responsibilities.

• For example, a Decorator object containing a user interface component can add a
decoration like a border or shadow to the component, or it can add functionality like
scrolling and zooming.

• We can add two decorations simply by nesting one Decorator object within another,
and so on for additional decorations.

SVCE Page 69
Object Oriented Analysis and Design CS6502

• To accomplish this, each Decorator object must conform to the interface of its
component and must forward messages to it.

• The Decorator can do its job (such as drawing a border around the component) either
before or after forwarding a message.

Adapter

• Convert the interface of a class into another interface clients expect.

• Adapter lets classes work together that couldn't otherwise because of incompatible
interfaces.

• AKA Wrapper

Motivation

Applicability

SVCE Page 70
Object Oriented Analysis and Design CS6502

• you want to use an existing class, and its interface does not match the one you need.

• you want to create a reusable class that cooperates with unrelated or unforeseen
classes, that is, classes that don't necessarily have compatible interfaces.

• (object adapter only) you need to use several existing subclasses, but it's impractical
to adapt their interface by subclassing every one. An object adapter can adapt the
interface of its parent class.

An object adapter relies on object composition

Participants

• Target (Shape)

– defines the domain-specific interface that Client uses.

SVCE Page 71
Object Oriented Analysis and Design CS6502

• Client (DrawingEditor)

– collaborates with objects conforming to the Target interface.

• Adaptee (TextView)

– defines an existing interface that needs adapting.

• Adapter (TextShape)

adapts the interface of Adaptee to the Target interface

Collaborations

Clients call operations on an Adapter instance. In turn, the adapter calls Adaptee operations
that carry out the request

Consequences

• A class adapter adapts Adaptee to Target by committing to a concrete Adapter class.


As a consequence, a class adapter won't work when we want to adapt a class and all
its subclasses.

• lets Adapter override some of Adaptee's behavior, since Adapter is a subclass of


Adaptee.

• introduces only one object, and no additional pointer indirection is needed to get to
the adapter

TextShape::TextShape (TextView* t) {

_text = t;

void TextShape::BoundingBox (

Point& bottomLeft, Point& topRight

) const {

Coord bottom, left, width, height;

bottomLeft = Point(bottom, left);

SVCE Page 72
Object Oriented Analysis and Design CS6502

topRight = Point(bottom + height, left + width);

bool TextShape::IsEmpty () const {

return _text->IsEmpty();

Manipulator* TextShape::CreateManipulator () const {

return new TextManipulator(this);

Strategy

Intent

• Define a family of algorithms, encapsulate each one, and make them


interchangeable.

• Strategy lets the algorithm vary independently from clients that use it.

Also known as policy

Motivation

• Many algorithms exist for breaking a stream of text into lines. Hard-
wiring all such algorithms into the classes that require them isn't desirable
for several reasons:

• Clients that need linebreaking get more complex if they include the
linebreaking code. That makes clients bigger and harder to maintain,
especially if they support multiple linebreaking algorithms.

• Different algorithms will be appropriate at different times. We don't want


to support multiple linebreaking algorithms if we don't use them all.

• It's difficult to add new algorithms and vary existing ones when
linebreaking is an integral part of a client.

• Defining classes that encapsulate different linebreaking algorithms.

• An algorithm that's encapsulated in this way is called a strategy.


SVCE Page 73
Object Oriented Analysis and Design CS6502

• Suppose a Composition class is responsible for maintaining and updating


the linebreaks of text displayed

in a text viewer.

• Linebreaking strategies aren't implemented by the class Composition.

• They are implemented separately by subclasses of the abstract


Compositor class.

Compositor subclasses implement different strategies:

• SimpleCompositor implements a simple strategy that determines


linebreaks one at a time.

• TeXCompositor implements the TeX algorithm for finding linebreaks.


This strategy tries to optimize linebreaks globally, that is, one paragraph
at a time.

• ArrayCompositor implements a strategy that selects breaks so that each


row has a fixed number of items.

• It's useful for breaking a collection of icons into rows, for example.

• A Composition maintains a reference to a Compositor object.

• Whenever a Composition reformats its text, it forwards this responsibility


to its Compositor object.

• The client of Composition specifies which Compositor should be used by


installing the Compositor it desires into the Composition.

SVCE Page 74
Object Oriented Analysis and Design CS6502

Applicability

Use the Strategy pattern when

• many related classes differ only in their behavior. Strategies provide a


way to configure a class with one of many behaviors.

• you need different variants of an algorithm. For example, you might


define algorithms reflecting different space/time trade-offs. strategies can
be used when these variants are implemented as a class hierarchy of
algorithms [HO87].

• An algorithm uses data that clients shouldn't know about. Use the
Strategy pattern to avoid exposing complex, algorithm-specific data
structures.

• A class defines many behaviors, and these appear as multiple conditional


statements in its operations.

• Instead of many conditionals, move related conditional branches into


their own Strategy class.

Structure

SVCE Page 75
Object Oriented Analysis and Design CS6502

Participants

Strategy (Compositor)

• declares an interface common to all supported algorithms.

• Context uses this interface to call the algorithm defined by a


ConcreteStrategy.

ConcreteStrategy (SimpleCompositor, TeXCompositor, ArrayCompositor)

implements the algorithm using the Strategy interface

Context (Composition)

• is configured with a ConcreteStrategy object.

• maintains a reference to a Strategy object.

• may define an interface that lets Strategy access its data.

Collaborations

• Strategy and Context interact to implement the chosen algorithm.

SVCE Page 76
Object Oriented Analysis and Design CS6502

• A context may pass all data required by the algorithm to the strategy
when the algorithm is called.

• Alternatively, the context can pass itself as an argument to Strategy


operations.

• That lets the strategy call back on the context as required.

• A context forwards requests from its clients to its strategy.

• Clients usually create and pass a ConcreteStrategy object to the context;


thereafter, clients interact with the context exclusively.

• There is often a family of ConcreteStrategy classes for a client to choose


from.

Consequences

The Strategy pattern has the following benefits and drawbacks:

1. Families of related algorithms. Hierarchies of Strategy classes define a


family of algorithms or behaviors for contexts to reuse. Inheritance can help
factor out common functionality of the algorithms.

2. An alternative to subclassing. Inheritance offers another way to support a


variety of algorithms or behaviors.

can subclass a Context class directly to give it different behaviors.

• Mixes the algorithm implementation with Context's, making Context


harder to understand, maintain, and extend.

• can't vary the algorithm dynamically.

• Wind up with many related classes whose only difference is the


algorithm or behavior they employ.

• Encapsulating the algorithm in separate Strategy classes lets you vary the
algorithm independently of its context, making it easier to switch,
understand, and extend.

SVCE Page 77
Object Oriented Analysis and Design CS6502

Strategies eliminate conditional statements.

The Strategy pattern offers an alternative to conditional statements for


selecting desired behavior.

• Encapsulating the behavior in separate Strategy classes eliminates these


conditional statements.

For example, without strategies, the code for breaking text into lines could
look like

void Composition::Repair () {

switch (_breakingStrategy) {

case SimpleStrategy:

ComposeWithSimpleCompositor();

break;

case TeXStrategy:

ComposeWithTeXCompositor();

break;

// ...

// merge results with existing composition, if necessary

The Strategy pattern eliminates this case statement by delegating the


linebreaking task to a Strategy object:

void Composition::Repair () {

_compositor->Compose();

// merge results with existing composition, if necessary

SVCE Page 78
Object Oriented Analysis and Design CS6502

• Code containing many conditional statements often indicates the need to


apply the Strategy pattern.

• A choice of implementations. Strategies can provide different


implementations of the same behavior.

• The client can choose among strategies with different time and space
trade-offs.

• Clients must be aware of different Strategies. The pattern has a potential


drawback in that a client

must understand how Strategies differ before it can select the appropriate one.

Clients might be exposed to implementation issues

Communication overhead between Strategy and Context.

• The Strategy interface is shared by all concreteStrategy classes whether


the algorithms they implement are trivial or complex.

• times when the context creates and initializes parameters that never get
used.

Increased number of objects.

• Strategies increase the number of objects in an application.

• Can reduce this overhead by implementing strategies as stateless objects


that contexts can share.

• Any residual state is maintained by the context, which passes it in each


request to the Strategy object.

• Shared strategies should not maintain state across invocations.

Implementation

implementation issues:

SVCE Page 79
Object Oriented Analysis and Design CS6502

1. Defining the Strategy and Context interfaces.

• The Strategy and Context interfaces must give a concreteStrategy


efficient access to any data it needs from a context, and vice versa.

• One approach is to have Context pass data in parameters to Strategy .

• This keeps Strategy and Context decoupled.

• On the other hand,Context might pass data the Strategy doesn't need.

• Another technique has a context pass itself as an argument, and the


strategy requests data from the context explicitly.

• Alternatively, the strategy can store a reference to its context.

• Context must define a more elaborate interface to its data, which couples
Strategy and Context more closely.

2.Strategies as template parameters.

• In C++ templates can be used to configure a class with a strategy.

This technique is only applicable if

(1) the Strategy can be selected at compile-time, and

(2) it does not have to be changed at run-time.

• In this case, the class to be configured (e.g.,Context) is defined as a


template class that has a Strategy class as a parameter:

template <class AStrategy>

class Context {

void Operation() { theStrategy.DoAlgorithm(); }

// ...

private:

AStrategy theStrategy;

SVCE Page 80
Object Oriented Analysis and Design CS6502

};

• The class is then configured with a Strategy class when it's instantiated:

class MyStrategy {

public:

void DoAlgorithm();

};

Context<MyStrategy> aContext;

• Using Strategy as a template parameter also lets bind a Strategy to its


Context statically, which can increase efficiency.

3. Making Strategy objects optional.

Context checks to see if it has a Strategy object before accessing it. If there is
one, Context uses it normally.

• If there isn't a strategy, then Context carries out default behavior.

Sample Code

• The Composition class maintains a collection of Component instances,


which represent text and graphical elements in a document.

• A composition arranges component objects into lines using an instance of


a Compositor subclass, which encapsulates a linebreaking strategy.

• Each component has an associated natural size, stretchability, and


shrinkability.

• The stretchability defines how much the component can grow beyond its
natural size; shrinkability is how much it can shrink.

• The composition passes these values to a compositor, which uses them to


determine the best location for linebreaks.

SVCE Page 81
Object Oriented Analysis and Design CS6502

class Composition {

public:

Composition(Compositor*);

void Repair();

private:

Compositor* _compositor;

Component* _components; // the list of components

int _componentCount; // the number of components

int _lineWidth; // the Composition's line width

int* _lineBreaks; // the position of linebreaks

// in components

int _lineCount; // the number of lines

};

• When a new layout is required, the composition asks its compositor to


determine where to place linebreaks.

• The composition passes the compositor three arrays that define natural
sizes, stretchabilities,and shrinkabilities of the components.

• It also passes the number of components, how wide the line is, and an
array that the compositor fills with the position of each linebreak.

The compositor returns the number of calculated breaks The Compositor


interface lets the composition pass the compositor all the information it needs.

This is an example of "taking the data to the strategy":

class Compositor {

public:

SVCE Page 82
Object Oriented Analysis and Design CS6502

virtual int Compose(

Coord natural[], Coord stretch[], Coord shrink[],

int componentCount, int lineWidth, int breaks[]

) = 0;

protected:

Compositor();

};

void Composition::Repair () {

Coord* natural;

Coord* stretchability;

Coord* shrinkability;

int componentCount;

int* breaks;

// prepare the arrays with the desired component sizes

// ...

// determine where the breaks are:

int breakCount;

breakCount = _compositor->Compose(

natural, stretchability, shrinkability,

componentCount, _lineWidth, breaks

);

Known Uses

• The Booch components use strategies as template arguments.


SVCE Page 83
Object Oriented Analysis and Design CS6502

• The Booch collection classes support three different kinds of memory


allocation strategies: managed (allocation out of a pool),controlled
allocations/deallocations are protected by locks), and unmanaged (the
normal memory allocator).

• These strategies are passed as template arguments to a collection class


when it's instantiated.

• For example, an UnboundedCollection that uses the unmanaged strategy


is instantiated as UnboundedCollection.

Observer

Intent

• Define a one-to-many dependency between objects so that when one


object changes state, all its dependents are notified and updated
automatically.

• Also known as Dependents, Publish-Subscribe

Observer

SVCE Page 84
Object Oriented Analysis and Design CS6502

• The Observer pattern describes how to establish these relationships.

• The key objects in this pattern are subject and observer.

• A subject may have any number of dependent observers.

• All observers are notified whenever the subject undergoes a change in


state.

• In response, each observer will query the subject to synchronize its state
with the subject's state.

• This kind of interaction is also known as publish-subscribe.

• The subject is the publisher of notifications.

• It sends out these notifications without having to know who its observers
are.

• Any number of observers can subscribe to receive notifications.

Applicability

• When an abstraction has two aspects, one dependent on the other.


Encapsulating these aspects in separate

SVCE Page 85
Object Oriented Analysis and Design CS6502

objects lets vary and reuse them independently.

• When a change to one object requires changing others, and don't know
how many objects need to be

changed.

• When an object should be able to notify other objects without making


assumptions about who these objects

are.

Structure

Subject

• knows its observers.

• Any number of Observer objects may observe a subject.

• provides an interface for attaching and detaching Observer objects.

Observer

• defines an updating interface for objects that should be notified of


changes in a subject.

SVCE Page 86
Object Oriented Analysis and Design CS6502

ConcreteSubject

• stores state of interest to ConcreteObserver objects.

• sends a notification to its observers when its state changes.

ConcreteObserver

• maintains a reference to a concreteSubject object.

• stores state that should stay consistent with the subject's.

• implements the Observer updating interface to keep its state consistent


with the subject's.

• ConcreteSubject notifies its observers whenever a change occurs that


could make its observers' state inconsistent with its own.

• After being informed of a change in the concrete subject, a


ConcreteObserver object may query the subject for information.

• ConcreteObserver uses this information to reconcile its state with that of


the subject.

Consequences
SVCE Page 87
Object Oriented Analysis and Design CS6502

Abstract coupling between Subject and Observer.

• subject knows a list of observers, each conforming to the simple


interface of the abstract Observer class.

• The subject doesn't know the concrete class of any observer.

• Thus the coupling between subjects and observers is abstract and


minimal.

Support for broadcast communication.

• The notification that a subject sends needn't specify its receiver.

• The notification is broadcast automatically to all interested objects that


subscribed to it.

• The subject doesn't care how many interested objects exist; its only
responsibility is to notify its observers.

• This gives the freedom to add and remove observers at any time.

• observer handle or ignore a notification.

Unexpected updates.
• Observers have no knowledge of each other's presence, they can be blind
to the ultimate cost of changing the subject.

• A seemingly innocuous operation on the subject may cause a cascade of


updates to observers and their dependent objects.

• Dependency criteria that aren't well-defined or maintained usually lead to


spurious updates, which can be hard to track down.

Issues

1. Mapping subjects to their observers.

• A subject keep track of the observers it should notify - store references


to them explicitly in the subject.

SVCE Page 88
Object Oriented Analysis and Design CS6502

• use an associative look-up (e.g., a hash table) to maintain the subject-to-


observer mapping.

• Thus a subject with no observers does not incur storage overhead.

• This approach increases the cost of accessing

the observers.

2. Observing more than one subject:

• An observer to depend on more than one subject.

• For example, a spreadsheet may depend on more than one data source.

• Necessary to extend the Update interface in such cases to let the observer
know which subject is sending the notification.

• The subject can simply pass itself as a parameter in the Update operation,
thereby letting the observer know

which subject to examine.

3. Who triggers the update?

• The subject and its observers rely on the notification mechanism to stay
consistent.

what object actually calls Notify to trigger the update?

a. Have state-setting operations on Subject call Notify after they change the
subject's state.

Advantage

• clients don't have to remember to call Notify on the subject.

Disadvantage

• several consecutive operations will cause several consecutive updates,


which may
SVCE Page 89
Object Oriented Analysis and Design CS6502

be inefficient.

b. Make clients responsible for calling Notify at the right time.

Advantage

• client can wait to trigger the update until after a series of state changes
has been made, thereby avoiding needless intermediate updates.

Disadvantage

• clients have an added responsibility to trigger the update.

• Makes errors more likely, since clients might forget to call Notify.

4. Dangling references to deleted subjects.

• Deleting a subject should not produce dangling references in its


observers.

• Avoid dangling references - make the subject notify its observers as it is


deleted so that they can reset their reference to it.

5.Making sure Subject state is self-consistent before notification:

• Make sure Subject state is self-consistent before calling Notify, because


observers query the subject for its current state in the course of updating
their own state.

• self-consistency rule is easy to violate unintentionally when Subject


subclass operations call inherited operations.

• For ex, the notification in the following code sequence is trigged when
the subject is in an inconsistent state:

void MySubject::Operation (int newValue) {

BaseClassSubject::Operation(newValue);

// trigger notification

_myInstVar += newValue;

SVCE Page 90
Object Oriented Analysis and Design CS6502

// update subclass state (too late!) }

• Avoid this pitfall by sending notifications from template methods in


abstract Subject classes.

• Define a primitive operation for subclasses to override, and make Notify


the last operation in the template method, which will ensure that the
object is self-consistent when subclasses override Subject operations.

void Text::Cut (TextRange r) {

ReplaceRange(r); // redefined in subclasses

Notify();

6.Avoiding observer-specific update protocols:

the push and pull models.

• Implementations of the Observer pattern have the subject broadcast


additional information about the change.

• The subject passes this information as an argument to Update.

• The amount of information vary .

• The push model, the subject sends observers detailed information about
the change, whether they want it or not.

• The pull model; the subject sends nothing but the most minimal
notification, and observers ask for details explicitly thereafter.

• The pull model emphasizes the subject's ignorance of its observers.

• The push model assumes subjects know something about their observers'
needs.

• The push model might make observers less reusable, because Subject
classes make assumptions about Observer classes that might not always
be true.
SVCE Page 91
Object Oriented Analysis and Design CS6502

• The pull model may be inefficient, because Observer classes must


ascertain what changed without help from

the Subject.

7.Specifying modifications of interest explicitly:

• Can improve update efficiency by extending the subject's

• registration interface to allow registering observers only for specific


events of interest.

• When such an event occurs, the subject informs only those observers that
have registered interest in that event.

• use the notion of aspects for Subject objects.

• To register interest in particular events, observers are attached to their


subjects using

void Subject::Attach(Observer*, Aspect& interest);

• where interest specifies the event of interest.

• At notification time, the subject supplies the changed aspect to its


observers as a parameter to the Update operation.

void Observer::Update(Subject*, Aspect& interest);

8.Encapsulating complex update semantics:

• When the dependency relationship between subjects and observers is


particularly complex, an object that maintains these relationships might
be required.

• A ChangeManager:

• Minimize the work required to make observers reflect a change in their


subject.

SVCE Page 92
Object Oriented Analysis and Design CS6502

• For ex, if an operation involves changes to several interdependent


subjects,ensure that their observers are notified only after all the subjects
have been modified to avoid notifying observers more than once.

9. Combining the Subject and Observer classes.

• In Smalltalk, for example, the Subject and Observer interfaces are defined
in the root class Object, making them available to all classes.

Unit 3 – Case Study

Unit Syllabus : CASE STUDY

Case study – the Next Gen POS system, Inception -Use case Modeling - Relating Use cases –
include, extend and generalization - Elaboration - Domain Models - Finding conceptual
classes and description classes – Associations – Attributes – Domain model refinement –
Finding conceptual class Hierarchies - Aggregation and Composition

Case study: (Next generation POS system)

point-of-sale(POS)

 A POS system is a computerized application used (in part) to record sales and handle
payments; it is typically used in a retail store. It includes hardware components such
as a computer and bar code scanner, and software to run the system. It interfaces to
various service applications, such as a third-party tax calculator and inventory control.
These systems must be relatively fault-tolerant; that is, even if remote services are
temporarily unavailable (such as the inventory system), they must still be capable of
capturing sales and handling at least cash payments.

SVCE Page 93
Object Oriented Analysis and Design CS6502

 A POS system increasingly must support multiple and varied client-side terminals and
interfaces.

Layers Involved In POS System

 User Interface—graphical interface; windows.


 Application Logic and Domain Objects—software objects representing domain
concepts (for example, a software class named Sale) that fulfil application
requirements.
 Technical Services—general purpose objects and subsystems that provide supporting
technical services, such as interfacing with a database or error logging. These services
are usually application-independent and reusable across several systems.

Inception:

 The purpose of the inception step is not to define all the requirements, or generate a
believable estimate or project plan.
 Inception phase should be relatively short for most projects, such as one or a few
weeks long.
 The intent of inception is to establish some initial common vision for the objectives of
the project, determine if it is feasible, and decide if it is worth some serious
investigation in elaboration.

Artifacts May Start in Inception:

SVCE Page 94
Object Oriented Analysis and Design CS6502

Requirements:
 Requirements are capabilities and conditions to which the system and more broadly,
the project must conform.

Types of Requirements:
 Functional—features, capabilities, security.
 Usability—human factors, help, documentation.
 Reliability—frequency of failure, recoverability, predictability.
 Performance—response times, throughput, accuracy, availability, resource usage.
 Supportability—adaptability, maintainability, internationalization, configurability.
 Implementation—resource limitations, languages and tools, hardware.
 Interface—constraints imposed by interfacing with external systems.
 Operations—system management in its operational setting.
 Packaging
 Legal—licensing and so forth

2.USE-CASE MODEL

Use cases—stories of using a system—is an excellent technique to understand and describe


requirements.

SVCE Page 95
Object Oriented Analysis and Design CS6502

The UP defines the Use-Case Model within the Requirements discipline.


Essentially, this is the set of all use cases; it is a model of the system's functionality and
environment.

Notations:

An actor is something with behavior, such as a person (identified by role), computer system,
or organization; for example, a cashier.

A scenario is a specific sequence of actions and interactions between actors and


the system under discussion; it is also called a use case instance. It is one particular
story of using a system, or one path through the use case; for example, the scenario of
successfully purchasing items with cash, or the scenario of failing to purchase items because
of a credit card transaction denial.

Informally then, a use case is a collection of related success and failure scenarios that
describe actors using a system to support a goal. For example, here is a casual format use
case that includes some alternate scenarios:

Handle Returns

Main Success Scenario: A customer arrives at a checkout with items to return. The cashier
uses the POS system to record each returned item ...
Alternate Scenarios:
If the credit authorization is reject, inform the customer and ask for an alternate payment
method.
If the item identifier is not found in the system, notify the Cashier and suggest manual entry
of the identifier code (perhaps it is corrupted).
If the system detects failure to communicate with the external tax calculator system, ...

 Use cases are text documents, not diagrams, and use-case modeling is primarily an act
of writing text, not drawing. However, the UML defines a use case diagram to
illustrate the names of use cases and actors, and their relationships.

Use Case Types

Black-box use cases are the most common and recommended kind; they do not describe the
internal workings of the system, its components, or design. Rather, the system is described as
having responsibilities, which is a common unifying metaphorical theme in object-oriented
thinking—software elements have responsibilities and collaborate with other elements that
have responsibilities it is possible to specify what the system must do (the functional
requirements) without deciding how it will do it (the design).

SVCE Page 96
Object Oriented Analysis and Design CS6502

Formality Types

 brief—terse one-paragraph summary, usually of the main success scenario. The prior
Process Sale example was brief.
 casual—informal paragraph format. Multiple paragraphs that cover various scenarios.
The prior Handle Returns example was casual.
 fully dressed—the most elaborate. All steps and variations are written in detail, and
there are supporting sections, such as preconditions and success guarantees.

Fully Dressed Example: Process Sale


 Fully dressed use cases show more detail and are structured; they are useful in
order to obtain a deep understanding of the goals, tasks, and requirements.

Use Case UC1: Process Sale

Primary Actor: Cashier

Stakeholders and Interests:


- Cashier: Wants accurate, fast entry, and no payment errors, as cash drawer shortages are
deducted from his/her salary.
- Salesperson: Wants sales commissions updated.
- Customer: Wants purchase and fast service with minimal effort. Wants proof of purchase to
support returns.
- Company: Wants to accurately record transactions and satisfy customer interests.
Wants to ensure that Payment Authorization Service payment receivables are recorded.
Wants some fault tolerance to allow sales capture even if server components (e.g., remote
credit validation) are unavailable. Wants automatic and fast update of accounting and
inventory.
- Government Tax Agencies: Want to collect tax from every sale. May be multiple agencies,
such as national, state, and county.
- Payment Authorization Service: Wants to receive digital authorization requests in the
correct format and protocol. Wants to accurately account for their payables to the
store.

SVCE Page 97
Object Oriented Analysis and Design CS6502

Preconditions: Cashier is identified and authenticated.

Success Guarantee (Postconditions): Sale is saved. Tax is correctly calculated.


Accounting and Inventory are updated. Commissions recorded. Receipt is generated.
Payment authorization approvals are recorded.

Main Success Scenario (or Basic Flow):


1. Customer arrives at POS checkout with goods and/or services to purchase.
2. Cashier starts a new sale.
3. Cashier enters item identifier.
4. System records sale line item and presents item description, price, and running total.
Price calculated from a set of price rules.
Cashier repeats steps 3-4 until indicates ............

The Two-Column Variation:


The two-column or conversational format, which emphasizes the fact that there is an
interaction going on between the actors and the system.

Preconditions state what must always be true before beginning a scenario in the use case.
Preconditions are not tested within the use case; rather, they are conditions that are assumed
to be true. Typically, a precondition implies a scenario of another use case that has
successfully completed, such as logging in, or the more general "cashier is identified and
authenticated."

SVCE Page 98
Object Oriented Analysis and Design CS6502

Success guarantees (or postconditions) state what must be true on successful completion of
the use case.either the main success scenario or some alternate path. The guarantee should
meet the needs of all stakeholders.

Preconditions: Cashier is identified and authenticated.

Success Guarantee (Postconditions): Sale is saved. Tax is correctly calculated. Accounting


and Inventory are updated. Commissions recorded. Receipt is generated.
USE CASE
GUIDELINES:
 essential UI free style
 Terse use cases
 Black box use cases
 Actor and Actor goal perspective
 How to find use cases
– Choose system boundary
– Find primary actors
– Identify goals
– Define use cases that satisfy the goal

Elementary business processes:


 EBP(elementary business processes) is a term from the business process engineering
field,defined as:
 A task performed by one person in one place at one time, in response to a business
event, which adds measurable business value and leaves the data in a consistent state.
e.g., Approve Credit or Price Order.

RELATING USE CASES:

Use cases can be related to each other. For example, a subfunction use case such as Handle
Credit Payment may be part of several regular use cases, such as Process Sale and Process
Rental. Organizing use cases into relationships has no impact on the behavior or requirements of
the system. Rather, it is simply an organization mechanism to (ideally) improve communication
and comprehension of the use cases, reduce duplication of text, and improve management of the
use case documents.

3 types:
The include Relationship
The extend Relationship
The generalize Relationship

The include Relationship:


It is common to have some partial behavior that is common across several use cases. For
example, the description of paying by credit occurs in several use cases, including Process
Sale, Process Rental, Contribute to Lay-away Plan.
This is simply refactoring and linking text to avoid duplication.
SVCE Page 99
Object Oriented Analysis and Design CS6502

For example: UC1:


Process Sale
Main Success Scenario:
1 . Customer arrives at a POS checkout with goods and/or services to purchase.
7. Customer pays and System handles payment.
Extensions:
7b. Paying by credit: Include Handle Credit Payment. 7c. Paying by check:
Include Handle Check Pavment.

UC7: Process Rental


Extensions:
6b. Paying by credit: Include Handle Credit Payment.
UC12: Handle Credit Payment
Level: Subfunction Main Success Scenario:
1. Customer enters their credit account information.
2. System sends payment authorization request to an external Payment Authorization

Guideline of when to use the include relationship:


Use include when you are repeating yourself in two or more separate use cases and you want
to avoid repetition. Another motivation is simply to decompose an overwhelmingly long use
case into subunits to improve comprehension.

Terminology: Concrete, Abstract, Base, and Addition UseCases

A concrete use case is initiated by an actor and performs the entire behaviour desired by the
actor . These are the elementary business process use cases. For example, Process Sale is a
concrete use case.
Abstract use case is never instantiated by itself; it is a subfunction use case that is part of
another use case. Handle Credit Payment is abstract; it doesn't stand on its own, but is always
part of another story, such as Process Sale.

A use case that includes another use case, or that is extended or specialized by
another use case is called a base use case. Process Sale is a base use case with
respect to the included Handle Credit Payment subfunction use case.

On the other hand, the use case that is an inclusion, extension, or specialization is
called an addition use case. Handle Credit Payment is the addition use case in
the include relationship to Process Sale.

Addition use cases are usually abstract.

Base use cases are usually concrete.

The Extend relationship:

SVCE Page 100


Object Oriented Analysis and Design CS6502

– a dotted line labeled <<extend>> with an arrow toward the base case.
– The extending use case may add behavior to the base use case. The base class
declares “extension points”.
<<extend>>

ELABORATION

 Elaboration is the initial series of iterations during which the team does serious
investigation, implements (programs and tests) the core architecture, clarifies most
requirements, and tackles the high-risk issues.
 Elaboration often consists of between two and four iterations; each iteration is
recommended to be between two and six weeks
 Each iteration is timeboxed, meaning its end date is fixed; if the team is not likely to
meet the date, requirements are placed back on the future tasks list, so that the
iteration can end on time with a stable and tested release.

What Artifacts May Start in Elaboration?

1. Domain Model: This is a visualization of the domain concepts; it is similar to a static


information model of the domain entities.

2. Design Model: This is the set of diagrams that describes the logical design. This includes
software class diagrams, object interaction diagrams ,package diagrams, and so forth.

3. Software Architecture Document: A learning aid that summarizes the key architectural
issues and their resolution in the design. It is a summary of the outstanding design ideas and
their motivation in the system.

4. Data Model : This includes the database schemas, and the mapping strategies between
object and non-object representations.

5. Test Model: A description of what will be tested, and how.

6. Implementation Model: This is the actual implementation — the source code,


executables, database, and so on.

SVCE Page 101


Object Oriented Analysis and Design CS6502

7. Use-Case Storyboards ,UI Prototypes: A description of the user interface, paths of


navigation, usability models.

BEST PRACTICES THAT WILL MANIFEST IN ELABORATION INCLUDE:


 do short time boxed risk-driven iterations
 start programming early
 adaptively design, implement, and test the core and risky parts of the architecture
 test early, often, realistically
 adapt based on feedback from tests, users, developers
 write most of the use cases and other requirements in detail, through a series of
workshops, once per elaboration iteration.

Domain Models

A domain model is a visual representation of conceptual classes or real-world objects in a


domain of interest .They have also been called conceptual models, domain object models,
and analysis object models.
Using UML notation, a domain model is illustrated with a set of class diagrams in which no
operations are defined. It may show:
• domain objects or conceptual classes
• associations between conceptual classes
• attributes of conceptual classes
For example, Figure shows a partial domain model. It illustrates that the conceptual class of
Payment and Sale are significant in this domain, that a Pay-merit is related to a Sale in a way
that is meaningful to note, and that a Sale has a date and time. The details of the notation are
not important at this time.

SVCE Page 102


Object Oriented Analysis and Design CS6502

Domain Model—A Visual Dictionary of Abstractions


It visualizes and relates some words or conceptual classes in the domain. It also depicts an
abstraction of the conceptual classes, because there are many things one could communicate
about registers, Sales.
Domain Models Are not Models of Software Components
Domain model is a visualization of things in the real world domain of interest, not of
software components such as a Java or C++ class (see Figure 10.3), or software objects with
responsibilities. Therefore, the following elements are not suitable in a domain model:
• Software artifacts, such as a window or a database, unless the domain being modelled is of
software concepts, such as a model of graphical user interfaces.
• Responsibilities or methods.

Conceptual Classes:
The domain model illustrates conceptual classes or vocabulary in the domain. Informally, a
conceptual class is an idea, thing, or object. More formally, a conceptual class may be
considered in terms of its symbol, intension, and extension

SVCE Page 103


Object Oriented Analysis and Design CS6502

 Symbol—words or images representing a conceptual class.


 Intension—the definition of a conceptual class.
 Extension—the set of examples to which the conceptual class applies.
For example, consider the conceptual class for the event of a purchase transaction. I may
choose to name it by the symbol Sale. The intension of a Sale may state that it "represents the
event of a purchase transaction, and has a date and time." The extension of Sale is all the
examples of sales; in other words, the set of all sales.

Strategies to Identify Conceptual Classes:


Two techniques are presented in the following sections
1. Use a conceptual class category list.
2. Identify noun phrases

1.Use a Conceptual Class Category List:

SVCE Page 104


Object Oriented Analysis and Design CS6502

SVCE Page 105


Object Oriented Analysis and Design CS6502

Finding Conceptual Classes with Noun Phrase Identification


Identify the nouns and noun phrases in textual descriptions of a domain, and consider them as
candidate conceptual classes or attributes. The fully dressed use cases are an excellent
description to draw from for this analysis. For example, the current scenario of the Process
Sale use case can be used.

Main Success Scenario (or Basic Flow):


1. Customer arrives at a POS checkout with goods and/or services to purchase.
2. Cashier starts a new sale.
3. Cashier enters item identifier.
4. System records sale line item and presents item description, price, and running total.
Price calculated from a set of price rules. Cashier repeats steps 2-3 until indicates done.
5. System presents total with taxes calculated.
6. Cashier tells Customer the total, and asks for payment.
7. Customer pays and System handles payment.
8. System logs the completed sale and sends sale and payment information to the external
Accounting (for accounting and commissions) and Inventory systems (to update inventory).
9. System presents receipt.
10.Customer leaves with receipt and goods (if any).

Extensions (or Alternative Flows):


7a. Paying by cash:
1. Cashier enters the cash amount tendered.
2. System presents the balance due, and releases the cash drawer.
3. Cashier deposits cash tendered and returns balance in cash to Customer.

Domain Modelling Guidelines:

How to Make a Domain Model:


Apply the following steps to create a domain model:
1. List the candidate conceptual classes using the Conceptual Class Category. List and noun
phrase identification techniques related to the current requirements under consideration.
2. Draw them in a domain model.
3. Add the associations necessary to record relationships for which there is a

SVCE Page 106


Object Oriented Analysis and Design CS6502

need to preserve some memory.


4. Add the attributes necessary to fulfill the information requirements.

On Naming and Modeling Things: The Mapmaker

 Use the existing names in the territory.


 Exclude irrelevant features.
 Do not add things that are not there.

The Need for Specification or Description Conceptual Classes

When Are Specification Conceptual Classes Required

Add a specification or description conceptual class (for example, ProductSpecification)


when:
 There needs to be a description about an item or service, independent of the current
existence of any examples of those items or services.
 Deleting instances of things they describe (for example, Item) results in a loss of
information that needs to be maintained, due to the incorrect association of
information with the deleted thing.
 It reduces redundant or duplicated information

Uml notation in different perspective models:

SVCE Page 107


Object Oriented Analysis and Design CS6502

Domain model vs Design model:


 The Domain Model offers a conceptual perspective.
 The Design Model offers a specification or implementation perspective,

Lowering the Representational Gap:

DOMAIN MODEL:
ADDING ASSOCIATIONS

An association is a relationship between types (or more specifically, instances of those types)
that indicates some meaningful and interesting connection.

In the UML associations are defined as "the semantic relationship between two
or more classifiers that involve connections among their instances."

SVCE Page 108


Object Oriented Analysis and Design CS6502

UML Association Notation:


 An association is represented as a line between classes with an association name. The
ends of an association may contain a multiplicity expression indicating the numerical
relationship between instances of the classes.
 "reading direction arrow" indicates the direction to read the association name; it does
not indicate direction of visibility or navigation

Finding Associations—Common Associations List

SVCE Page 109


Object Oriented Analysis and Design CS6502

Association Guidelines:
 Too many associations tend to confuse a domain model rather than illuminate it. Their
discovery can be time-consuming, with marginal benefit.
 Avoid showing redundant or derivable associations
SVCE Page 110
Object Oriented Analysis and Design CS6502

Roles:
 Each end of an association is called a role. Roles may optionally have:
1.name
2.multiplicity expression
3.navigability

Multiplicity:
 Multiplicity defines how many instances of a class A can be associated with one
instance of a class B

Examples of multiplicity expressions

SVCE Page 111


Object Oriented Analysis and Design CS6502

Naming Associations
Name an association based on a TypeName-VerbPhrase-TypeName format where the verb
phrase creates a sequence that is readable and meaningful in the model context.
Association names should start with a capital letter, since an association represents a
classifier of links between instances; in the UML, classifiers should start with a capital letter.
Two common and equally legal formats for a compound association name are:
• Paid-by
• PaidBy

SVCE Page 112


Object Oriented Analysis and Design CS6502

Multiple Associations Between Two Types

Example partial domain model:

DOMAIN MODEL:
ADDING ATTRIBUTES:

 An attribute is a logical data value of an object. For example, a receipt (which


reports the information of a sale) normally includes a date and time.

SVCE Page 113


Object Oriented Analysis and Design CS6502

UML Attribute Notation:


 Attributes are shown in the second compartment of the class box . Their type may
optionally be shown.

Valid Attribute Types:


 The attributes in a domain model should preferably be simple attributes or data types.
Very common attribute data types include: Boolean, Date, Number, String (Text), Time.
Other common types include: Address, Color, Geometries (Point, Rectangle), Phone
Number, Social Security Number, Universal Product Code (UPC), SKU, ZIP or postal codes,
enumerated types.

Data Types
Attributes should generally be data types

Attributes in the NextGen Domain Model

SVCE Page 114


Object Oriented Analysis and Design CS6502

DOMAIN MODEL REFINEMENT:

Association Classes:

Association class, in which we can add features to the association itself. ServiceContract
may be modeled as an association class related to the association between Store and
AuthorizationService.

In the UML, this is illustrated with a dashed line from the association to the association class.
visually communicates the idea that a Service-Contract and its attributes are related to the
association between a Store and AuthorizationService, and that the lifetime of the
ServiceContract is dependent on the relationship.

Guidelines:

SVCE Page 115


Object Oriented Analysis and Design CS6502

An attribute is related to an association.


 Instances of the association class have a life-time dependency on the association.
 There is a many-to-many association between two concepts, and information
associated with the association itself.
 The presence of a many-to-many association is a common clue that a useful
association class is lurking in the background somewhere; when you see one, consider
an association class.

Aggregation and Composition:

Aggregation is a kind of association used to model whole-part relationships between things.


The whole is called the composite.
For instance, physical assemblies are organized in aggregation relationships, such as a Hand
aggregates Fingers.

Aggregation in the UML

Aggregation is shown in the UML with a hollow or filled diamond symbol at the composite
end of a whole-part association.

SVCE Page 116


Object Oriented Analysis and Design CS6502

Aggregation is a property of an association role.The association name is often excluded in


aggregation relationships since it is typically thought of as Has-part.

Composite Aggregation—Filled Diamond

Composite aggregation, or composition, means that the part is a member of only


one composite object, and that there is an existence and disposition dependency of the part on
the composite. For example, a hand is in a composition relationship to a finger.

How to Identify Aggregation

Consider showing aggregation when:


 The lifetime of the part is bound within the lifetime of the composite —there is a
create delete dependency of the part on the whole.
 There is an obvious whole-part physical or logical assembly.
 Some properties of the composite propagate to the parts, such as the location.
 Operations applied to the composite propagate to the parts, such as destruction,
movement, recording.

Benefit of Showing Aggregation

It clarifies the domain constraints regarding the eligible existence of the part
independent of the whole. In composite aggregation, the part may not exist outside of the
lifetime of the whole.
Operations—such as copy and delete—applied to the whole often propagate to the parts

Aggregation in the POS Domain Model

In the POS domain, the SalesLineItems may be considered a part of a composite Sale;
in general, transaction line items are viewed as parts of an aggregate transaction. In addition
to conformance to that pattern, there is a create-delete dependency of the line items on the
Sale—their lifetime is bound within the lifetime of the Sale. By similar justification,
ProductCatalog is an aggregate of Product-Specifications

Role name:

SVCE Page 117


Object Oriented Analysis and Design CS6502

Each end of an association is a role, which has various properties, such as:
 name
 multiplicity
A role name identifies an end of an association and ideally describes the role played by
objects in the association. Figure shows role name examples.

Roles as Concepts vs. Roles in Associations

Roles in associations are appealing because they are a relatively accurate way to express the
notion that the same instance of a person takes on multiple (and dynamically changing) roles
in various associations. I, a person, simultaneously or in sequence, may take on the role of
writer, object designer, parent, and so on.
On the other hand, roles as concepts provides ease and flexibility in adding unique attributes,
associations, and additional semantics. Furthermore, the implementation of roles as separate
classes is easier because of limitations of current popular object-oriented programming
languages—it is not convenient to dynamically mutate an instance of one class into another,
or dynamically add behavior and attributes as the role of a person changes.

SVCE Page 118


Object Oriented Analysis and Design CS6502

Derived Elements:

A derived element can be determined from others. Attributes and associations are the most
common derived elements
For example, a Sale total can be derived from SalesLineItem and Product-Specification
information. In the UML, it is shown with a "/" preceding the element name.

Derived Attributes Related To Multiplicity:

As another example, a SalesLineItem quantity is actually derivable from the number of


instances of Items associated with the line item.

SVCE Page 119


Object Oriented Analysis and Design CS6502

Qualified Associations

A qualifier may be used in an association; it distinguishes the set of objects at the far end of
the association based on the qualifier value. An association with a qualifier is a qualified
association.

In fig 1 For example, ProductSpecifications may be distinguished in a ProductCatalog


by their itemID,

In fig 2 qualification reduces the multiplicity at the far end from the qualifier, usually down
from many to one

Reflexive Associations:
A concept may have an association to itself; this is known as a reflexive association.

Ordered Elements:

If associated objects are ordered, this can be shown as in Figure, For example, the
SalesLineItems must be maintained in the order entered

SVCE Page 120


Object Oriented Analysis and Design CS6502

Using Packages to Organize the Domain Model:

UML Package Notation

A UML package is shown as a tabbed folder.Subordinate packages may be shown within it.
The package name is within the tab if the package depicts its elements; otherwise, it is
centered within the folder itself.

Ownership And References:

An element is owned by the package within which it is defined, but may be referenced in
other packages. In that case, the element name is qualified by the package name using the
pathname format PackageName::ElementName

Package Dependencies:

SVCE Page 121


Object Oriented Analysis and Design CS6502

If a model element is in some way dependent on another, the dependency may be shown with
a dependency relationship, depicted with an arrowed line. A package dependency indicates
that elements of the dependent package in some way know about or are coupled to elements
in the target package.
For example, if a package references an element owned by another, a dependency exists.
Thus, the Sales package has a dependency on the Core Elements package.

Package Indication without Package Diagram

At times, it is inconvenient to draw a package diagram, but still desirable to indicate the
package that the elements are a member of.
In this situation, include a note (dog-eared note) on the diagram, as illustrated,

How to Partition the Domain Model

To partition the domain model into packages, place elements together that:
 are in the same subject area — closely related by concept or purpose
 are in a class hierarchy together
 participate in the same use cases
 are strongly associated

POS Domain Model Packages:

SVCE Page 122


Object Oriented Analysis and Design CS6502

Core/Misc Package:

A Core/Misc package is useful to own widely shared concepts or those without an obvious
home. In later references, the package name will be abbreviated to Core.
There are no new concepts or associations particular to this iteration in this Package.

For example(package diagram for sale):

SVCE Page 123


Object Oriented Analysis and Design CS6502

UML ACTIVITY DIAGRAM AND MODELING

 Rake symbol-Expanding an activity in another activity diagram

 Signals

– To show time triggering an action, cancellation request

SVCE Page 124


Object Oriented Analysis and Design CS6502

Notations:

 Transition

 Events

 state

SVCE Page 125


Object Oriented Analysis and Design CS6502

Unit – 4 – Applying Design Patterns

Unit Syllabus : APPLYING DESIGN PATTERNS

System sequence diagrams - Relationship between sequence diagrams and use cases- Logical
architecture and UML package diagram – Logical architecture refinement - UML class
diagrams – UML interaction diagrams - Applying GoF design patterns

SYSTEM SEQUENCE DIAGRAMS

 Input and output events

 Use Case(UC) - how actors interact with the system

 During interaction actor generates system events.

 UML include sequence diagram and interaction diagram.

 SSD - a picture,shows one particular scenario of a UC.

 ex., enterItem event

SSD needs:

 To design, a software has to handle events, execute and take a response.

 Software system react to 3 things :

-External events

-Timer events

-Faults/exception

 Investigate and define system behavior

SSD versus Sequence Diagram

 Illustrates input and output events related to the system under discussion.

 Associated with use-case realization in the logical view of system development.

SVCE Page 126


Object Oriented Analysis and Design CS6502

 Sequence Diagrams (Not System Sequence Diagrams) display object interactions


arranged in time sequence.

Process sale scenario

SSD with derived case

SVCE Page 127


Object Oriented Analysis and Design CS6502

System Events and System Boundary

 To identify the system events, system boundary is critical.

 For the purpose of software development, the system boundary is chosen to be the
software system itself.

SVCE Page 128


Object Oriented Analysis and Design CS6502

Naming System Events and Operations

System event

1) External input event generated by an actor.

2) Initiates a responding operation by system.

System operation

Operation invoked in response to system event.

SSD with Usecase text:

SVCE Page 129


Object Oriented Analysis and Design CS6502

ITERATIVE & EVOLUTIONARY SSDs

 Don’t create SSDs for all scenarios

 SSDs are useful to understand the scenarios/to document

 SSDs are part of the use case model

 SSDs created in elaboration not in inception

LOGICAL ARCHITECTURE AND UML PACKAGE DIAGRAMS

• A layer is a large grouping of classes, packages, or subsystems.

• Higher layers call upon the services of lower layers.

• Types of layered architecture:

– Strict layered

– Relaxed layered

SVCE Page 130


Object Oriented Analysis and Design CS6502

Typical Layers

• User interface

• Application logic and domain objects

• Technical services – subsystems that support low-level functions.

• In strict layering, a layer only calls upon services in the layer directly below it.

Software Architecture

• Decisions about the organization of a software system

• Selection of structural elements and their interfaces, along with their behavior.

• Organization of elements into progressively larger systems

• The logical architecture is the large-scale organization of the classes into packages
(namespaces), subsystems, and layers.

• No decision about how they’re deployed

UML :Package Diagrams

• It provides a way to group elements

• It can group classes,packages,use cases..

• Large coupling system,dependency between package is important,represented by


dashed arrow line, an arrow pointing towards dependency package.

Reverse-Engineering

• UML case tools is to reverse engineer the source-code and generate a package
diagram automatically.

SVCE Page 131


Object Oriented Analysis and Design CS6502

Package
UI Domain

Swing Web Sales

UI

UI::Swing UI::Web

Swing Web
Domain::Sales
Domain

Sales

UML fully qualified circle-cross

Layers Benefits

• Reduces coupling & dependency.

• Improves cohesion,increases reuse potential and increases clarity.

• Related complexity is encapsulated and decomposable.

• Lower layers contain reusable function.

• Some layers can be distributed.

• Logical segmentation.

Layers Architectural Pattern:

SVCE Page 132


Object Oriented Analysis and Design CS6502

• GUI

• Application: handles presentation layer requests, workflow, session state,


window/page transitions

• Domain: app layer requests, domain rules, domain services

• Business infrastructure

• Tech services

• Foundation: threads, math, network I/O

Cohesive Responsibilities

• Maintain a seperation of concerns

• Object responsibilities should not mixed up with of other layers responsibilities

• UI layer focus on UI work

• Application/Domain layer focus on application logic.

• UI should not do application logic.

SVCE Page 133


Object Oriented Analysis and Design CS6502

• Application logic should not trap UI events.

Domain Model Vs. Application Logic Layer

• Domain layer - Part of the software

• Domain Model - Part of the conceptual perspective analysis

• Lower representation gap between real world domain and software design.

Tiers, Layers, Partitions

• Tiers were originally logical layers, but now the term has come to mean physical
nodes.

• Service Oriented Architecture

• Layers are vertical slices, while partitions are horizontal divisions of subsystems
within a layer. E. g. tech services may contain Security and Reporting

Model-View Separation

• Model is a synonym for the domain layer of objects

• View is a synonym for UI objects.

• Don’t connect non-UI objects directly to UI objects. Don’t let a Sale object reference
directly a Jframe

• Don’t put application logic, such as tax calculation, in a UI object’s methods. UI


objects should only initialize the elements, receive UI events, and delegate requests
for application logic to non-UI objects

Why Model-View Separation?

• Focus on domain processes rather than the UI

• Allow separate development of UI and the model

• Minimize impact of requirements changes in the UI on the domain layer

• Allow views to be connected to existing domain layer

• Multiple views of same domain object

• Allow porting of UI to another framework

• Allow execution of model independently of UI

SVCE Page 134


Object Oriented Analysis and Design CS6502

LOGICAL ARCHITECTURE REFINEMENT

• No application layer

• Using small set of instructive elements to convey big ideas

• Responsibilities of control/session object in the application layer are handled by


register object.

Inter-Layer & Inter-package coupling

Inter-Layer & Inter-package Scenarios

SVCE Page 135


Object Oriented Analysis and Design CS6502

System operations & Layers

• Hiding UI objects

• System operations invoked on the system are request generated by an actor via UI
layer onto the application layer.

SVCE Page 136


Object Oriented Analysis and Design CS6502

Layers pattern issues

• Logical vs Process & Deployment views of the architecture

– Architectural layers are logical,not deployment

– All layers deployed within the same process on the same node.

• Is application layer optional?

– If present,controlling flow of work.

– Applctn layer useful when any of the below is true:

• In multiple UI, applctn layer - adapters.

• Distributed system,domain layer - different node than UI.

• Domain layer cannot maintain session state.

• Defined workflow in terms of controlled order of windows.

• Fuzzy set membership in different layers

– Classification(differentiation) - high vs low (or) specific vs general

• eg., Java technologies,log4J open source logging framework.

• Web application, stuts frameworks

• Contraindications & liabilities for layers

– Adding layers cause problem

– Layer pattern is several core architectural pattern.

• Virtual machine and O.S

– Higher layers access lower layer services.

– Application written in higher layers in the architecture.

• Information systems : Three- tier architecture

– Description of vertical tiers is:

SVCE Page 137


Object Oriented Analysis and Design CS6502

• Interface

• Application logic

• Storage

Model – View Seperation & “Upward” communication

• How windows obtain information to display?

– Polling/pull-from-above model of display updates.

• Typical situations of this case include:

– Monitoring application

– Simulation application

• Push-from-below model of display update is required.

SVCE Page 138


Object Oriented Analysis and Design CS6502

UML CLASS DIAGRAM

• Ilustrate classes,interface& association

• +/- visibility,compartments.

• Multiple perspectives

• Domain model – conceptual perspective

• Design model – Design Class Diagram(DCD)

• Classifier – Behavorial and structural features

• Two types: Regular classes & Interfaces

Design Class Diagram

SVCE Page 139


Object Oriented Analysis and Design CS6502

UML Attributes


UML Attributes: Attribute Text & Association lines

• Attribute as association line:

1. Navigation arrow

2. Multiplicity @ target end

3. Rolename @ target end

4. No association name

SVCE Page 140


Object Oriented Analysis and Design CS6502

Attribute text Vs Association lines

• Attribute text notation for data type obj

• Association line notation for others

• Both are semantically equal

• Showing association line to other classes

UML notation @ association end

Navigation arrow – End of an association

SVCE Page 141


Object Oriented Analysis and Design CS6502

• Rolename – attribute name & multiplicity

• Property string

– {Ordered}/{Ordered,List}

– {unique} Set of unique elements

– {List} user defined keywords

public class Register

{private int id;

Private Sale currentSale;

Private Store location;

//}

Methods in class diagram

Stereotypes, Profile & Tags

• Stereotypes – refinement of an existing modeling in UML profile

• Profile – Specialize specific domain

• Tags – declares set of tags

• UML defines many stereotypes :

– <<destroy>> user defined

SVCE Page 142


Object Oriented Analysis and Design CS6502

UML properties & Property Strings

• Property – named value (characteristic of an element)

• Visibility – a property of an operation

UML Property string{name1=value1,name2=value2}

{abstract , visibility = public}

{abstract}  {abstract = true} //without a value

{abstract} – example of a constraint and a property


string

Dependency

• Illustrated with dashed arrow line from client to supplier

• Indicates client element has knowledge of another supplier

• Change in the supplier could affect the client

• Kinds of dependency,

– Have attribute of supplier type

SVCE Page 143


Object Oriented Analysis and Design CS6502

– Sending message to supplier,visibility of supplier should:

• An attribute, parameter variable, local, global variable,class


visibility(invoke static methods)

• Receiving parameter of supplier type

• Supplier is a super class /interface

• Special UML line to show super class:

– Implementation of an interface

– Attributes

• A sale has dependency on SalesLineItems by virtue of association line.

• Second dashed arrow dependency line is redundant.

• Dependency line is to depict global, parameter, local, static – method dependency


between objects.

Dependency Labels

• Optional / help a tool with code generation

• Dependency line can be labeled with keywords or stereotypes.

Interfaces

• Interface implementation also called as interface realization.

SVCE Page 144


Object Oriented Analysis and Design CS6502

• Provides interface to clients and interface dependency/required interface.

Dfferent notations to show interfaces in UML

SVCE Page 145


Object Oriented Analysis and Design CS6502

Composition over Aggregation

• Also called as composite aggregation

• Composition relationship implies:

– An instance of the part belongs to one composite instance @ a time

– Part must always belong to composite

– Composite responsible of its parts either by itself


creating/deleting/collaborating with other objects.

• Guideline:

– Lifetime of the part is bound with in the lifetime of the composite.

– Logical / physical whole part assembly.

– Properties of composite propagate to the parts

– Operations applied to composite propogate to the parts.

Qualified Association

• Looking up things by a key(Hash map).

• Multiplicity reduces @ the target end of the association(many to one)

SVCE Page 146


Object Oriented Analysis and Design CS6502

Association class

• Represented by dashed line from association to association class

• It treats association itself as a class & model it with attributes, operation & other
features.

Singleton classes

• Only one instance of a class instantiated – singleton pattern

• Class can be marked with a ‘1’ in the upper right corner of the compartment

SVCE Page 147


Object Oriented Analysis and Design CS6502

Active class

• Class of an active object

• Shown with double vertical lines on left & right side of class box

UML Interaction Diagram

• How object interact via messages?

• How interaction diagrams related interms of logic & process flow?

• Dynamic object modeling


SVCE Page 148
Object Oriented Analysis and Design CS6502

• Types:

– Sequence diagram

– Communication interaction diagram

Sequence Diagram

• Fence format, new object added to the right

Communication Diagram

• Object can be placed anywhere in the diagram

SVCE Page 149


Object Oriented Analysis and Design CS6502

UML Interaction diagram notation

• Lifeline box equals an instance of a class

• “sale” instance has a shorthand notation

• Message Expression syntax:

return = msg(parameter: parameter type) :returntype

– > Parantheses excluded if no parameters

– > Type information excluded if obvious.

Sequence Diagram Notation

• Lifeline boxes & Lifelines

– Actual lifelines

– Dashed ->UML

– Solid/dashed ->UML2

• Messages

– Message expression – filled arrow (solid line between vertical lines)

SVCE Page 150


Object Oriented Analysis and Design CS6502

– Ex., starting message(found message)

• Lifeline boxes & Lifelines

– Actual lifelines

– Dashed ->UML

– Solid/dashed ->UML2

• Messages

– Message expression – filled arrow (solid line between vertical lines)

– Ex., starting message(found message)

Illustrating Reply or returns

• Message syntax

– Return var=message(parameter)

– Reply(return) message line @ the end of activation bar

• Getdate--

• -- adate

SVCE Page 151


Object Oriented Analysis and Design CS6502

Message to “self” or “this”

• It shows a message being sent from an object to itself

• Nested activation bar

Creation of Instances

• Object creation notation

• “new” operator call the constructor

SVCE Page 152


Object Oriented Analysis and Design CS6502

Object lifelines & Object destruction

Object lifelines & Object destruction

Diagram frames

• Frames / Diagram frames,interaction frames

SVCE Page 153


Object Oriented Analysis and Design CS6502

• Frames -regions/fragments of the diagram

• Operator/ label & guard

Frame formats

Frame Meaning
operator

Alt Alternative fragment for mutual exclusion conditional logic expressed in


the guards

Loop Loop fragment while guard is true.

Also write loop(n) to indicate looping n times.

Specification will be enhanced to define a FOR loop, loop(I,1,10)

Opt Optional fragment that executes if guard is true

SVCE Page 154


Object Oriented Analysis and Design CS6502

Par Parallel fragments that execute in parallel

region Critical regions within which only one thread can run

SD notation

• Looping – Loop frame notation

• Conditional message :

– OPT : around 1/more messages.

guard placed over the related lifeline.

• Conditional messages in UML 1.x style – still useful?

SVCE Page 155


Object Oriented Analysis and Design CS6502

• Mutually exclusive conditional messages

– ALT : placed around the mutually exclusive conditional messages

Nesting of frames

SVCE Page 156


Object Oriented Analysis and Design CS6502

Interaction diagrams

• Interaction occurrence/ interaction use – reference to an interaction within another.

• Interaction overview diagrams – interaction occurences

• Two related frames:


SVCE Page 157
Object Oriented Analysis and Design CS6502

– Frame around entire sequence diagram -sd tag

– Actual interaction occurrence – frame tagged ref

Messages to classes to invoke static methods

Polymorphic messages & cases

SVCE Page 158


Object Oriented Analysis and Design CS6502

Asynchronous & synchronous calls

• Asynchronous message

– doesnot wait for a response

– doesn’t block

– Used in multi threaded environment

– UML notation – stick arrow message

• Synchronous calls / blocking

– Filled arrow.

Communication Diagram Notation

• Links

– Instance of an association

– Connection path between two object

– Multiple messages share same single link

SVCE Page 159


Object Oriented Analysis and Design CS6502

Message to “self” or “this”

Instance creation

SVCE Page 160


Object Oriented Analysis and Design CS6502

Message number sequencing

SVCE Page 161


Object Oriented Analysis and Design CS6502

• Complex sequence numbering

Conditional messages

Mutually exclusive conditional paths

SVCE Page 162


Object Oriented Analysis and Design CS6502

Iteration or looping

SVCE Page 163


Object Oriented Analysis and Design CS6502

Messages to a classes to invoke static(class) methods

Polymorphic messages & use cases

SVCE Page 164


Object Oriented Analysis and Design CS6502

Asynchronous & synchronous calls

APPLYING GOF DESIGN PATTERNS:


Design patterns represent common software problems and the solutions to those problems
in a formal manner. They were inspired by a book written by architect Christopher
Alexander. Patterns were introduced in the software world by another book: "Design
Patterns: Elements of Reusable Object-Oriented Software", by Erich Gamma, Richard
Helm, Ralph Johnson, and John Vlissides. These people were nicknamed the "Gang of
Four" for some mysterious reason. The Gang of Four describes 23 design patterns. The

SVCE Page 165


Object Oriented Analysis and Design CS6502

design patterns are becoming common knowledge, which leads to better communication.
To summarize design patterns save time, energy while making your life easier.
The following GOF design patterns are explored in the subsequent sections :
 Adapter
 Analysis
 Factory
 Singleton
 Strategy
 Composite

SINGLETON
The singleton pattern deals with situations where only one instance of a class must be
created. Take the case of a system administrator or superuser. This person has the right to
do everything in a computer system. In addition we will also have classes representing
normal users. Therefore we must ensure that these classes have no access to the super
user constructor. The solution to this problem in C++ and Java is to declare the superuser
constructor private. The superuser class itself has a private static attribute sysadmin,
which is initialised using the class constructor. Now we get an instance of the super user
class with a public static method that returns sysadmin. Here is the class diagram:

FACTORY METHOD
The Factory Method pattern deals with situations where at runtime one of several similar
classes must be created. Visualize this as a factory that produces objects. In a toy factory
for instance we have the abstract concept of toy. Every time we get a request for a new
toy a decision must be made - what kind of a toy to manufacture. Similarly to the
Singleton pattern the Factory Method pattern utilises a public static accessor method. In
our example the abstract Toyfactory class will have a getInstance() method, which is
inherited by its non abstract subclasses.

SVCE Page 166


Object Oriented Analysis and Design CS6502

ADAPTER
Sometimes you will have two classes that can in principle work well together, but they
can't interface with each other for some reason. This kind of problem occurs when
travelling abroad and you carry an electric shaver with you. Although it will work
perfectly when you are at home. There can be problems in a foreign country, because of a
different standard voltage. The solution is to use an adapter. Let's turn our attention back
to the software domain. Here we will have an interface which defines new methods for
example getElectricity2. An adapter class will wrap around the Shaver class. The adapter
class will implement the interface with the new method.

PROXY
The Proxy pattern deals with situations where you have a complex object or it takes a
long time to create the object. The solution to this problem is to replace the complex
object with a simple 'stub' object that has the same interface. The stub acts as a body
double. This is the strategy used by the Java Remote Method Invocation API. The reason
to use the proxy pattern in this case is that the object is on a remote server causing
network overhead. Other reasons to use the proxy can be restricted access (Java applets
for example) or time consuming calculations.

DECORATOR
The Decorator is usually a subclass, that is a body double for its superclass or another
class with identical interface. The goal of the Decorator pattern is to add or improve the
capabilities of the super class.

SVCE Page 167


Object Oriented Analysis and Design CS6502

COMPOSITE
The composite is often encountered in GUI packages like for instance the Java Abstract
Windwing Toolkit (AWT) or Microsoft Foundation (MFC) classes. All objects in this
pattern have a common abstract superclass that descibes basic object conduct. The base
class in the MFC hierarchy is CObject. It provides functions for debugging and
serialization. All the MFC classes even the most basic ones inherit these facilities.

OBSERVER AND MVC


An application with Model - View - Controller setup usually uses the Observer Pattern. In
a Java webserver environment the model will be represented by Java classes
encompassing the business logic, the view is represented by Java Server Pages which
display HTML in the client's browser and we will have a Servlets as Controllers. The
observer pattern strategy is to have view components take subscriptions for their model.
This ensures that they will get notified if the model changes.

Figure - Observer and MVC Class Diagram


TEMPLATE
In the good old days before OOP writing functions was the recommended thing to do. A
sort algorithm would be implement by half dozen of functions, one sort function for
integers, one sort function for floating points, one sort function for doubles etc. These
functions are so similar that nobody in their right mind will type them letter by letter.
Instead a programmer will write a template and copy the template several times. After
SVCE Page 168
Object Oriented Analysis and Design CS6502

that it's just a matter of writing down datatypes as appropriate. Thanks to OOP and the
Template Design Pattern less code is required for this task. First we need to define an
abstract Template class let's call it SortTemplate and it will have methods sort, compare
and process (performs one cycle of the algorithm). Then we define concrete classes for
each datatype. These classes are subclasses of SortTemplate and implement the compare
and process methods.

STRATEGY
The Strategy Design Pattern makes it possible choose an implementation of an algorithm
at run time. The implementation classes implement the same interface. In the case of the
Java AWT Layout classes, the common interface is LayoutManager.

Unit 5 Coding and Testing

Unit Syllabus : CODING AND TESTING

Mapping design to code – Testing: Issues in OO Testing – Class Testing – OO


Integration Testing –GUI Testing – OO System Testing
SVCE Page 169
Object Oriented Analysis and Design CS6502

MAPPING DESIGN TO CODE:

OO development is iterative
Interaction diagrams and DCD’s will be used as the input to the code generation
process.
OOA/D artifacts feed into implementation model in a traceable manner
Some tools generate partial code from UML
But programming not trivial code generation step
Programmers make changes as they work out the details
Therefore, Expect and plan for change and deviation from design during
programming.

Mapping Designs to Code


Process: Write source code for
Class and interface definitions
Method definitions
Work from OOA/D artifacts
Create class definitions from Design Class Diagrams (DCDs)
Create methods from Interaction diagrams.

Design Class Diagrams


DCDs contain class or interface names, classes, method and simple attributes.
These are sufficient for basic class definitions.
Elaborate from associations to add reference attributes.

Reference Attributes
Reference Attributes are suggested by associations and navigability in a class
diagram.
Note that reference attributes may be implied rather than explicit on a class
diagram. You may have to ask “How is this association accomplished.”
Example: A product specification reference on a Sales Line Item.
Each end of an association is a role. Reference Attributes are often suggested by
role names.
(use role names as the names of reference attributes).

From DCD to Java class

public class SalesLineItem


SVCE Page 170
{
private int quantity;

private ProductDescription description;

public SalesLineItem(ProductDescription desc, int qty) { ... }


Object Oriented Analysis and Design CS6502

Creating methods from Interaction Diagrams


Interaction Diagrams are used to specify methods.
They give most of the details for what the method does.

{
ProductDescription desc = catalog.ProductDescription(id);
currentSale.makeLineItem(desc, qty);
}

enterItem(id, qty) 2: makeLineItem(desc, qty)


:Register :Sale

1: desc := getProductDescription(id)
SVCE Page 171

:Product
Catalog
Object Oriented Analysis and Design CS6502

From Interaction diagram to method

Containers and Collections


Where an object must maintain visibility to a group of other objects, such as
a group of Sales Line Items in a Sale, object-oriented languages often use an
intermediate container or collection.
These will be suggested by a multiplicity value greater than one on a class
diagram.

SVCE Page 172


Object Oriented Analysis and Design CS6502

Collection classes

Sale
public class Sale
{ isComplete : Boolean
... time : DateTime SalesLineItem
lineItems
private List lineItems = new ArrayList(); becomeComplete() quantity : Integer
1..*
} makeLineItem()
getSubtotal()
makePayment()
getTtotal()

A collection class is necessary to


maintain attribute visibility to all the
SalesLineItems.

Defining the Sale.makeLineItem Method

SVCE Page 173


Object Oriented Analysis and Design CS6502

{lineItems.add( new
SalesLineItem(desc,qty));
}

Order of Implementation
First implement classes that are loosely coupled then move on to classes that
are closely coupled.

Store
7
address : Address
1 2
name : Text
3 ProductDescription
ProductCatalog
addSale(...)
description : Text
... price : Money
1 1..* itemID : ItemID
getProductDesc(...)
...

1
1 Sale
5
6
Register isComplete : Boolean 4
time : DateTime SalesLineItem
...
becomeComplete() quantity : Integer
endSale() 1 1..*
makeLineItem(...)
Test – Driven
enterItem(...) or Test – FirstmakePayment(...)
Development getSubtotal()
makeNewSale()
getTotal()
makePayment(...)
...

SVCE Page 174 1


* Payment

amount : Money
1
...
Object Oriented Analysis and Design CS6502

Excellent practice promoted by the Extreme Programming (XP) method, and


applicable to the UP and other iterative methods are Test – driven
development (TDD) or Test – first development.
Unit test code is written before the code to be tested, and the developer
writes unit testing code for all production code.
------------------------------------------------------------------------------------------------
ISSUES IN OBJECT ORIENTED TESTING
 Identify the testing issues raised by object oriented software.
 First is the levels of testing , this requires clarification of object oriented
units.
Units for OO testing

• A unit
– Is a smallest software component that can be compiled and
executed.
– Is a software component that would never be assigned to more than
one developer to develop.

For large applications – many classes.

Hence to define an object – oriented unit as the work of one person, which ends
up as a set of class operations.

Class-as-unit has advantages :

- A class has state chart that describes its behavior.


- OO integration testing – to check cooperation of separately tested
classes.

Implications of Composition & encapsulation

 Composition – central design strategy in object oriented software


development.
 Composition creates need for very strong unit testing.
 Unit composed with other units – coupling and cohesion are applicable.
 Encapsulation needs highly cohesive and loosely coupled.

SVCE Page 175


Object Oriented Analysis and Design CS6502

 Main implication of Composition:


 Good at unit testing but burden at integration level testing.

Example:

 Identify 3 main classes from windshield wiper system .


 Pseudocode for interface for these classes:

• Lever and dial classes sense physical events on respective devices.


• When these methods execute, they report their position to wiper class
• Lever and dial are independent devices
• They interact when lever is in INT (intermittent) state.
Question raised by encapsulation is where should this interaction be
controlled?

• Concept of encapsulation – classes should know only about and operate


on their own.
• Thus the lever does not know dial position and vice versa.
• The problem is Wiper class needs to know both positions.
• Solution is Lever and dial always report their positions and wiper figures
out what it must do?
• Wiper is the main program – contains basic logic of whole system
Second choice:

• To make Lever class the smart object because it knows when it is in the
intermittent state.
• With this choice , when the response to the lever event puts the lever in
the INT state, a method gets the dial status and simply tells the wiper
what speed is needed.

SVCE Page 176


Object Oriented Analysis and Design CS6502

• With this choice three classes are more tightly coupled and hence less
reusable.
• Problem – lever in INT and a dial event occurs, no message would be
sent to wiper because there is no reason for the lever to get dial position.

Third choice

• Make the wiper a main program


• Use a Has relation to lever and dial classes
• With this choice the Wiper class senses physical events of dial and lever
• This focus wiper class to be active and keeps polling.

Comparison of three choices:

• First choice – v. little coupling among three classes ( can be reused )


• Second choice & third choice – more coupling (less reusability)

SVCE Page 177


Object Oriented Analysis and Design CS6502

• More encapsulated the classes are, the more they are composed ( more
reusable) & tested.

Implications of inheritance

• If a given class inherits attributes /operations from super classes , stand


alone complication criterion of a unit is sacrificied.
• Inheritance – use of attributes and operations from super classes, the
criteria of a unit is sacrificed.
• Binder suggests using flattened classes as an answer.
• Flattened classes – original class extended to include all attributes and
operations that it inherits.
• Unit testing on flattened classes solves inheritance problem but another
problems arise:
– A flattened class is not part of final system so uncertainty arises.
– Methods may not be sufficient to test.
• To solve these:
• Add special purpose test methods.
– not part of final system
– Test methods may be faulty.

An example to show the implication of Inheritance.

SVCE Page 178


Object Oriented Analysis and Design CS6502

 Checking Account and savings account are stand alone units to test.
 If we do not flatten we would not have access to balance attributes.

Implications of polymorphism

• Same methods apply to different objects.


• Considering classes as units imply that any issues of polymorphism will
be covered by Class/unit testing
Levels of OO Testing :

SVCE Page 179


Object Oriented Analysis and Design CS6502

 Operation/Method – Identical to Unit testing.


 Class (Intraclass testing)
 Integration testing (Interclass testing)
 System Testing
--------------------------------------------------------------------------------------------
CLASS TESTING
A unit is a
Is a smallest chunk that can be compiled by itself
A single procedure/function
Something small that it would be developed by one person
Methods as units
Method is equivalent to a procedure.
Traditional software requires stubs and driver test program to supply test
cases & record results.
OO testing – stubs are classes that can be instantiated
Main program – act as driver that provide test cases.
There are 2 approaches:
Methods as units
Classes as units
Pseudocode for OO testing
Testing Object-Oriented NextDate
Rewritten here in object-oriented style
One Abstract Class—CalendarUnit
Classes -– testIt
– Date
– Day

SVCE Page 180


Object Oriented Analysis and Design CS6502

– Month
– Year
CRC - Class Responsibility Cards for each class.
Class: CalendarUnit

Class: testIt

SVCE Page 181


Object Oriented Analysis and Design CS6502

Class: Date

Program graphs for testIt & Date class

SVCE Page 182


Object Oriented Analysis and Design CS6502

Program graph for Day class

Unit testing for Date.increment

SVCE Page 183


Object Oriented Analysis and Design CS6502

Classes as units
3 views of a class:
Static class
Compile-time view
Execution time view

Pseudocode testing for windshieldWiper class

Unit testing for windshieldWiper class

SVCE Page 184


Object Oriented Analysis and Design CS6502

SVCE Page 185


Object Oriented Analysis and Design CS6502

SVCE Page 186


Object Oriented Analysis and Design CS6502

------------------------------------------------------------------------------------------------
--------------------

OO INTEGRATION TESTING

SVCE Page 187


Object Oriented Analysis and Design CS6502

Levels of Testing

Requirements System
Specification Testing

Preliminary Integration
Design Testing

Detailed
Unit
Design
Testing

Coding

Operations/methods as units – 2 levels of integration testing

To integrate methods into class

To integrate one class with other classes

Class as unit -2 steps

If flattened classes are used, original class hierarchy must be restored.

If test methods are added, they must be removed

GOALS/ PURPOSE OF INTEGRATION TESTING

Presumes previously tested units. It is not system testing. It tests functionality


between unit and system level.

UML support for Integration Testing

In UML defined OO software, collaboration & sequence diagrams are the basis
for integration testing. At the system level – UML description is comprised of
various levels of use cases, use case diagram, class definitions and class
diagrams.

SVCE Page 188


Object Oriented Analysis and Design CS6502

After this level, integration level details are added. Collaboration diagram
shows message traffic among classes

SVCE Page 189


Object Oriented Analysis and Design CS6502

Approaches to Integration Testing

1. Based on Functional Decomposition

Top-Down
Bottom-Up
Sandw ich
Big Bang

2. Based on Call Graph

Pair-wise
Neighborhood

3. Based on Paths

MM-Paths
. Atomic System Functions

Pair-wise – a class is tested in terms of adjacent classes that either send or


receive messages from class being tested.Other classes are considered as stubs.

Pairs of classes for integration testing

SVCE Page 190


Object Oriented Analysis and Design CS6502

At the class level, the behavior model of class is state chart.State charts serve as
test cases. At a higher level, it is difficult to combine state charts.

Neighborhood integration – neighborhood of Date is entire graph.

For testIt , neighborhood is just Date.Ultra-center reduces the maximum


distance to other nodes.

Start with ultra-center and add nodes that are one edge away, then add nodes
that are 2 edges away and so on..

------------------------------------------------------------------------------------------------
----------------
SVCE Page 191
Object Oriented Analysis and Design CS6502

Sequence diagram

A sequence diagram has 2 levels - at system/use case level

-Class level

Sequence diagram traces execution time path .Serve as basis for integration
testing.

Statements 2,3 & 4 are already tested methods.

------------------------------------------------------------------------------------------------
---------------------

MM-paths for OO software

• Method/Message path

SVCE Page 192


Object Oriented Analysis and Design CS6502

• MM-path starts with a method and ends when it reaches a method that
does not issue any messages of its own.

• MM-path in OO software is a sequence of method executions linked by


messages.

• An Atomic System Function(ASF) is an MM-path that begins with an


input port and ends with an output port event.

Pseudocode for OO calendar

-------

--

SVCE Page 193


Object Oriented Analysis and Design CS6502

------------------------------------------------------------------------------------------------

Framework for OO data flow integration testing

Data can get values from inheritance tree.Data can be defined at various stages
of message passing.Program graphs are formed

Event and message driven petri nets

SVCE Page 194


Object Oriented Analysis and Design CS6502

Definition

EMDPN is a quadripartite directed graph (P,D,M,S,In,Out) - 4 nodes & 2


mappings

petrinet

Petrinet transitions are method execution paths.

SVCE Page 195


Object Oriented Analysis and Design CS6502

Inheritance induced data flow

Message induced data flow

SVCE Page 196


Object Oriented Analysis and Design CS6502

GUI TESTING

• GUI – application driven.

• GUI application helps testers to perform little Integration testing.

• Test a GUI application – begin with user input events and all system
output events.

Example

A sample GUI built with Visual Basic

SVCE Page 197


Object Oriented Analysis and Design CS6502

High level complete view of application. State are external appearances of GUI.

SVCE Page 198


Object Oriented Analysis and Design CS6502

Unit testing- GUI Applications

Functional and structural testing occurs at this level.

Methods:Run test cases from a specifically coded driver that would provide
values for input data and check output values against expected values.

Use GUI as a test bed. Good for small applications.Harder to capture text
execution results.

Integration testing – GUI Applications

Methods: Concentrates all logic in one place and simply uses the status of the
option buttons as conditions in IF test

SVCE Page 199


Object Oriented Analysis and Design CS6502

Second – more object oriented – have methods in each option button object.

System testing – GUI Applications

Event driven petri nets to describe threads to be tested.Port i/p and o/p events
in currency conversion GUI.

SVCE Page 200


Object Oriented Analysis and Design CS6502

Atomic system functions and data places that needed to make EPDN of the
GUI.

The next step is building an EPDN description of the currency conversion GUI
is to develop EPDN’s for individual atomic system functions.

SVCE Page 201


Object Oriented Analysis and Design CS6502

System level threads are built by composing atomic system function into
sequence.

SVCE Page 202


Object Oriented Analysis and Design CS6502

Consider set T of threads their ASF sequences are.

T1=<s1,s4,s6,s7>

T2=<s1,s2,s6,s7>

T3=<s3,s1,s6,s8>

T4=<s5,s1,s7,s8>

SVCE Page 203


Object Oriented Analysis and Design CS6502

Threads in set T has following coverages.

Every atomic system function.

Every port input.

Every port output.

Set T constitutes minimum level of system testing for the currency conversion
GUI.

------------------------------------------------------------------------------------------------

UML BASED SYSTEM TESTING

SYSTEM TESTING:

• System Testing is independent of application.


• A System tester need no know If implementation is in procedural or
object oriented code.
PRIMITIVES OF SYSTEM TESTING:

• Port Input
• Output events.

System functions and the categories:

project Inception

• Customer /User describes the application in general terms.


• Take form of “User Stories” – precursors to use cases.
• From these three types of system functions defined.
Categories - System Functions:

• Evident – obvious one


• Hidden – Might not be discovered immediately
• Frill – bells and whistles that so often occur.

SVCE Page 204


Object Oriented Analysis and Design CS6502

Types of usecases in system testing with examples

High level –Use Cases

• Use case development begins with high level view.


• Have a short , structured naming convention for various level of usecases.
• HLUC – insufficient for test case identification.
• Capture a narrative description of something that happens in the system
to be built.

SVCE Page 205


Object Oriented Analysis and Design CS6502

Essential Usecases

• Essential usecases add actor and system events to high level usecase.
• Actors – sources of system level inputs.
• Actors – people, devices, adjacent systems or abstractions such as time.
• The numbering of actor actions and system responses show their
approximate sequences in time.
• Essential usecases add actor and system events to high level usecase.
• Actors – sources of system level inputs.
• Actors – people, devices, adjacent systems or abstractions such as time.
• The numbering of actor actions and system responses show their
approximate sequences in time.

SVCE Page 206


Object Oriented Analysis and Design CS6502

Expanded EUC

• Add pre and post condition information , information alternative


sequence of events and a cross reference to the system functions.

SVCE Page 207


Object Oriented Analysis and Design CS6502

• More usecases are identified and added.

SVCE Page 208


Object Oriented Analysis and Design CS6502

Real Usecases :

• Convert every usecase statement to GUI specific statement.


• EX: Enter a U.S Dollar amount – Enter 125 in txtdollar.

UML Based System Testing

 There are four identifiable levels with corresponding coverage metrics for
GUI applications.
 Two of these are dependent on UML specification.
Level 1
SVCE Page 209
Object Oriented Analysis and Design CS6502

 The first level is to test the system functions.


 These are cross referenced in the extended essential use cases and can
easily build an incidence matrix.

 Incidence matrix help cover seven system functions.


 One way to derive test cases from real use cases that correspond to
extended essential use cases 1,2,5 and 6.
 Use case preconditions are test case preconditions.
 Sequence of actor actions and system responses map directly into
sequences of user input events and system output events.
 EEUC 1,2,5 & 6 – example for regression test cases, because EEUC5
covers four system functions and EEUC6 covers three.
Level 2

• Develop test cases from all of the real use cases.

SVCE Page 210


Object Oriented Analysis and Design CS6502

SVCE Page 211


Object Oriented Analysis and Design CS6502

Level 3:

• Derive test cases from finite state machines derived from finite state
description of the external appearance of the GUI.
• A test case from this formulation is a circuit.
• Nine test cases are derived.

Level 4:

SVCE Page 212


Object Oriented Analysis and Design CS6502

• Derive test cases from state – based event tables.


• Called exhaustive level.
• An extremely detailed view of system testing that is likely redundant with
integration and even unit level test cases.

State Chart Based System Testing:

 State charts are a finite basis for system testing.


 State chart are at class level in UML.
 No easy way to compose statecharts of several classes to get system level
state chart.
 Translate each class level statechart into a set of EPDNS and then
compose the EPDN’s.

SVCE Page 213

Das könnte Ihnen auch gefallen