OOAD Notes
OOAD Notes
1. Introduction to OOAD
2. Unified Process
3. UML diagrams
i. Use Case
ii. Class Diagrams
iii. Interaction diagrams
iv. State Diagrams
v. Activity Diagrams
vi. Package,
vii. component and Deployment Diagrams
______________________________________________________________________________
1.What is Object-Oriented Analysis and Design? OR What is analysis and design? ( 6 TIMES)
FAQS 16 MARKS
1.Briefly explain the different phases Unified process. (UNIV- 9 TIMES) [16]
3. Explain UML State Machine Diagrams and Modeling. (UNIV- 7 TIMES) [16]
4. Discuss about UML Deployment and Component Diagrams. Draw the diagrams for a
banking application. (UNIV- 6 TIMES) [16]
5. List various UML diagrams and explain the purpose of each diagram. (UNIV- 1 TIME) [16]
1.INTRODUCTION TO OOAD:
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 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.
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.
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.
Classification:
Broadly classified as
Structural
Behavioral
__________________________________________________________________________
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:
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
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.
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:
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.
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.
1. 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.
An initial business case containing at least a clear formulation of the product vision - the core
requirements - in terms of functionality, scope, performance, capacity, technology base.
Success criteria (example: revenue projection).
An initial risk assessment.
An estimate of the resources required to complete the elaboration phase.
2.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
The products and artifacts described in the exit criteria of the previous phase.
The plan approved by the project management, and funding authority, and the resources
required for the elaboration phase have been allocated.
A detailed software development plan, with an updated risk assessment, a management plan, a
staffing plan, a phase plan showing the number and contents of the iteration , an iteration plan,
and a test plan
The development environment and other tools
A baseline vision, in the form of a set of evaluation criteria for the final product
A domain analysis model, sufficient to be able to call the corresponding architecture
‘complete’.
An executable architecture baseline.
3.Construction
The product and artifacts of the previous iteration. The iteration plan must state the iteration
specific goals
Risks being mitigated during this iteration.
Defects being fixed during the iteration.
4.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.
The product and artifacts of the previous iteration, and in particular a software product
sufficiently mature to be put into the hands of its users.
An update of some of the previous documents, as necessary, the plan being replaced by a
“postmortem” analysis of the performance of the project relative to its original and revised
success criteria;
A brief inventory of the organization’s new assets as a result this cycle.
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.
Agile UP
Agile process implies a light and adaptive process, nimble in response to changing needs.
3.UML diagrams
• Actors:
• A role that a user plays with
respect to the system ,
including human users and
other systems. e.g.in animate
physical objects (e.g. robot); an
external system that needs
some information from the
current system
• Non-human Actor
• Show non human actors in a
different manner, usually as a
Inventory rectangle
• Non human actors are usually
• Use case:
System
A system is shown as a
rectangle, labeled with the
system name
Association Relationship
Association
Extend
Generalization
Uses
Include
Extend Relationship
Uses Relationship
When a use case uses
another process, the
relationship can be shown
with the uses relationship
This is shown as a solid line
with a closed arrow point
and the <<uses>> keyword
• Considered in terms of
– Symbol
– Intension
– Extension
CONCEPTUALCLASS - ASSOCIATIONS
ASSOCIATIONS - DEFINITION
• In UML, associations are defined as semantic relation between two or more classifiers
that involve connections among their instances
ASSOCIATION - EXAMPLE
ASSOCIATION
ASSOCIATION - MULTIPLICITY
• Multiplicity
– How many instances of class A can be associated with one instance of class B
– Context dependent
ASSOCIATION - MULTIPLICITY
ATTRIBUTES
ATTRIBUTES - EXAMPLE
Payment
CheckPaym
CashPaymen CreditPay ent
t ment
Payment
Pays-for Sale
amount : Money 1 1
• 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
o 100% of the conceptual Superclass’s definition should be applicable to the
subclass.
o The subclass must conform to 100% of the Superclass’s:
attributes
associations
GENERALIZATION - GUIDELINE
CONCEPTUALCLASSHIERARCHY
ABSTRACT CLASS
Composition
o Whole-part aggregation
o Strongly coupled
o Also known as composite aggregation
Aggregation
o Whole-part relationship
o Loosely coupled
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
2.Communication Diagram
Strengths
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
2.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
1. Lifeline Box
2. Message Expression
3. Singleton Objects
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
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
__________________________________________________________________
Each diagram usually represents objects of a single class and tracks different states of its
objects through the system
Introduction
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
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
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
3. Role mutators
Objects that change their role
Ex: A Person changing roles from being a student to a staff
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
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.
NESTED STATES
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
n.
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
Guidelines
Layer
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
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.
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
Component Elements
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
o Provided
Required
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
External View
INTERNAL VIEW
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
o Shows assignment of concrete software architects(executable files) to
computational nodes
o It shows,
o Deployment of software elements to the physical architecture
o Communication between the physical elements
o Basic element – node
1.Node
element that provides the execution environment for the components of a system
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
Symbol:
Solid Line
Dashed Arrow
______________________________________________________________________________
2.Design Patterns
2.1creational
2.2 Factory method
2.3 Structural
2.4 Bridge
2.5 Adapter
3.Behavioral Patterns
3.1 Strategy
3.2 Observer
_________________________________________________________________________
FAQs TWO MARKS
FAQs 16 MARKS
1. What is GRASP? Explain the following GRASP patterns: Creator, Information Expert, Low
Coupling, and High Cohesion. (UNIV- 9 TIMES) [16]
2. Write a short note on adapter, singleton, factory and observer patterns. (UNIV- 9 TIMES)
3. Explain the concept of creator. (UNIV- 1 TIME) [7] 4. What is visibility? List four ways
that visibility can be achieved from Object A to Object B. (UNIV- 1 TIME) [4]
_____________________________________________________________________________
For example, "a Sale is responsible for creating SalesLineItems " (a doing), or "a Sale is
responsible for knowing its total" (a knowing).
Sale objects have been given a responsibility to create Payments , which is invoked with
a makePayment message and handled with a corresponding makePayment method.
Further, the fulfillment of this responsibility requires collaboration to create the payment
object and invoke its constructor.
9 GRASP patterns
– Information Expert
– Creator
– Controller
– Low Coupling
– High Cohesion
– Polymorphism
– Pure Fabrication.
– Indirection
1.CREATOR
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 records A.
B closely uses A.
Example Problem
Sale
time
Contains
1..*
Product
Sales Description
LineItem * Described-by 1
description
quantity price
itemID
So Sale class aggregates SalesLineItem objects so Sale class creates the SalesLineItem
objects.
2.INFORMATION EXPERT
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
Sale time
...
time t = getTotal : Sale 1 *: st = getSubtotal lineItems[ i ] :
getTotal()
SalesLineItem
1
1.1: p := getPrice() SalesLineItem
Contains
quantity
1..* :Product getSubtotal()
Product Description
Sales Description
LineItem * Described-by 1
Product
Description
description
quantity price description
price
itemID itemID
New method getPrice()
3.CONTROLLER
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 )
Ex:Process Sale controller or ProcessSale Handler
presses button
: Cashier
actionPerformed( actionEvent )
UI Layer :SaleJFrame
presses button
Cashier
actionPerformed( actionEvent )
1: makeLineItem(itemID, qty)
Domain Layer :Sale
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()
3. HIGH COHESION
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.
: Register : Sale
makePayment()
create()
p : Payment
addPayment( p )
: Register : Sale
makePayment()
makePayment()
create() : Payment
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.
5.LOW COUPLING
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
makePayment() 1: makePayment()
: Register :Sale
1.1. create()
:Payment
Assuming that the Sale must eventually be coupled to knowledge of a Payment, having
Sale create the Payment does not increase coupling.
2. DESIGN PATTERNS
Purpose of patterns
• Behavioral patterns characterize the ways in which classes or objects interact and
distribute responsibility.
• 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
• 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.
• 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
• 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
• 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.
Room class
• Use an enumeration Direction in C++ implementations to specify the north, south, east,
and west sides of a room:
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:
};
• Room is the concrete subclass of MapSite that defines the key relationships between
components in the maze.
• It maintains references to other MapSite objects and stores a room number. The number
will identify rooms in the maze.
public:
Room(int roomNo);
private:
MapSite* _sides[4];
int _roomNumber;
};
The following classes represent the wall or door that occurs on each side of a room.
public:
Wall();
};
public:
Room * OtherSideFrom(Room*);
private:
Room* _room1;
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*);
private:
// ...
};
RoomNo could do a look-up using a linear search, a hash table, or even a simple array.
• 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 () {
aMaze->AddRoom(r1);
aMaze->AddRoom(r2);
r1->SetSide(East, theDoor);
r2->SetSide(West, theDoor);
return aMaze;
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
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 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.
by replacing these prototypical objects with different ones. This is an example of the
Prototype 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.
______________________________________________________________________________
• Define an interface for creating an object, but let subclasses decide which class to
instantiate.
Motivation
• Frameworks use abstract classes to define and maintain relationships between objects.
• 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.
• 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.
This creates a dilemma: The framework must instantiate classes, but it only knows about abstract
classes, which it cannot instantiate
Solution
• It encapsulates the knowledge of which Document subclass to create and moves this
knowledge out of the framework.
Factory Method
Applicability
classes delegate responsibility to one of several helper subclasses, and you want to localize the
knowledge of which helper subclass is the delegate
• are concerned with how classes and objects are composed to form larger structures.
• 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.
• 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
• 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
Flyweight
• Applications that use lots of objects must pay careful attention to the cost of each object.
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.
________________________________________________________________________
2.4 Bridge
The Bridge pattern separates an object's abstraction from its implementation so that you can vary
them independently.
Decorator
• 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.
• 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.
2.5 Adapter
• Adapter lets classes work together that couldn't otherwise because of incompatible
interfaces.
• AKA Wrapper
Motivation
Applicability
• 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.
Participants
• Target (Shape)
• Client (DrawingEditor)
• Adaptee (TextView)
• Adapter (TextShape)
Collaborations
Clients call operations on an Adapter instance. In turn, the adapter calls Adaptee operations that
carry out the request
Consequences
• 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 (
) const {
return _text->IsEmpty();
3. BEHAVIOURAL PATTERNS
3.1Strategy
• Define a family of algorithms, encapsulate each one, and make them interchangeable.
• Strategy lets the algorithm vary independently from clients that use it.
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.
• It's difficult to add new algorithms and vary existing ones when linebreaking is an
integral part of a client.
• Suppose a Composition class is responsible for maintaining and updating the linebreaks
of text displayed
in a text viewer.
• 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.
• The client of Composition specifies which Compositor should be used by installing the
Compositor it desires into the Composition.
Applicability
• 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
Participants
Strategy (Compositor)
Context (Composition)
Collaborations
• A context may pass all data required by the algorithm to the strategy when the algorithm
is called.
• Clients usually create and pass a ConcreteStrategy object to the context; thereafter,
clients interact with the context exclusively.
Consequences
• 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.
The Strategy pattern offers an alternative to conditional statements for selecting desired
behavior.
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;
// ...
The Strategy pattern eliminates this case statement by delegating the linebreaking task to a
Strategy object:
void Composition::Repair () {
_compositor->Compose();
• Code containing many conditional statements often indicates the need to apply the
Strategy pattern.
• 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.
• 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.
• 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.
Implementation
implementation issues:
• The Strategy and Context interfaces must give a concreteStrategy efficient access to
any data it needs from a context, and vice versa.
• 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.
• Context must define a more elaborate interface to its data, which couples Strategy and
Context more closely.
• 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:
class Context {
// ...
private:
AStrategy theStrategy;
};
• 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.
Context checks to see if it has a Strategy object before accessing it. If there is one, Context uses
it normally.
Sample Code
• 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.
class Composition {
public:
Composition(Compositor*);
void Repair();
private:
Compositor* _compositor;
// in components
};
• 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.
class Compositor {
public:
) = 0;
protected:
Compositor();
};
void Composition::Repair () {
Coord* natural;
Coord* stretchability;
Coord* shrinkability;
int componentCount;
int* breaks;
// ...
int breakCount;
breakCount = _compositor->Compose(
);
Known Uses
• 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.
________________________________________________________________
3.2 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.
Observer
• 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.
• It sends out these notifications without having to know who its observers are.
Applicability
• When an abstraction has two aspects, one dependent on the other. Encapsulating these
aspects in separate 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
Observer
• defines an updating interface for objects that should be notified of changes in a subject.
ConcreteSubject
ConcreteObserver
• 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
• subject knows a list of observers, each conforming to the simple interface of the abstract
Observer class.
• Thus the coupling between subjects and observers is abstract and minimal.
• 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.
Unexpected updates.
• Observers have no knowledge of each other's presence, they can be blind to the ultimate
cost of changing the subject.
ISSUES
• A subject keep track of the observers it should notify - store references to them
explicitly in the 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.
• The subject and its observers rely on the notification mechanism to stay consistent.
a. Have state-setting operations on Subject call Notify after they change the subject's state.
Advantage
Disadvantage
• several consecutive operations will cause several consecutive updates, which may
be inefficient.
Advantage
• client can wait to trigger the update until after a series of state changes has been made,
thereby avoiding needless intermediate updates.
Disadvantage
• Makes errors more likely, since clients might forget to call Notify.
• Avoid dangling references - make the subject notify its observers as it is deleted so that
they can reset their reference to it.
• 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.
• For ex, the notification in the following code sequence is trigged when the subject is in
an inconsistent state:
BaseClassSubject::Operation(newValue);
// trigger notification
_myInstVar += newValue;
• 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.
Notify();
• 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 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.
• The pull model may be inefficient, because Observer classes must ascertain what
changed without help from
the Subject.
• 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.
• To register interest in particular events, observers are attached to their subjects using
• At notification time, the subject supplies the changed aspect to its observers as a
parameter to the Update operation.
• A ChangeManager:
• Minimize the work required to make observers reflect a change in their subject.
• In Smalltalk, for example, the Subject and Observer interfaces are defined in the root
class Object, making them available to all classes.
_____________________________________________________________
2.Inception
2.1 Use case Modeling
2.2 Relating Use cases
2.3 include, extend and generalization
3 Elaboration
3.1 Domain Models
3.2 Finding conceptual classes and description classes
3.3 Associations
3.4 Attributes
3.5 Domain model refinement
3.6 Finding conceptual class Hierarchies
3.7 Aggregation and Composition
_____________________________________________________________________________
10. List out the steps to finding use cases. (UNIV- 1 TIME)
FAQs 16 MARKS
1.Explain with an example, how use case modeling is used to describe functional requirements.
Identify the actors, scenario and use cases for example. (UNIV-9 TIMES)[16]
2. Describe the strategies used to identify conceptual classes. Describe the steps to create
domain model used for representing conceptual classes. [OR] Explain the method of
identifying the classes using the common class approach with an example. (UNIV- 8
TIMES) [16]
3. Write briefly about elaboration and discuss the differences between Elaboration and Inception
with examples. (UNIV- 1 TIME) [16]
4. Explain the relationships that are possible among the classes in the UML representation with
your own example. (UNIV- 1 TIME) [16]
7. Explain about the Next Gen POS System. (UNIV- 1 TIME) [6]
8. Describe the basic activities in OO analysis and explain how use case modeling is useful in
analysis. (UNIV- 1 TIME) [10]
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.
A POS system increasingly must support multiple and varied client-side terminals and
interfaces.
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.
Requirements:
Requirements are capabilities and conditions to which the system and more broadly, the
project must conform.
Types of Requirements:
________________________________________________________________________
Notations:
An actor is something with behavior, such as a person (identified by role), computer system, or
organization; for example, a cashier.
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.
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 use cases show more detail and are structured; they are useful in
order to obtain a deep understanding of the goals, tasks, and requirements.
- 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.
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.
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
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
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.
– 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>>
____________________________________________________________________________
2.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.
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.
6. Implementation Model: This is the actual implementation — the source code, executables,
database, and so on.
Domain Models
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 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
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.
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.
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."
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
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
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
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.
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
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:
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 is shown in the UML with a hollow or filled diamond symbol at the composite end
of a whole-part association.
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.
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
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:
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 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.
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.
As another example, a SalesLineItem quantity is actually derivable from the number of instances
of Items associated with the line item.
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 2 qualification reduces the multiplicity at the far end from the qualifier, usually down from
many to one
Reflexive Associations:
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
_____________________________________________________________________________
4. What do you mean by sequence number in UML? Where and for what it is used? (UNIV- 2
TIMES)
5. Define package and draw the UML notation for Package. (UNIV- 2 TIMES)
9. What are interactive diagrams? And list out the components. (UNIV- 1 TIME)
FAQs 16 MARKS
1. Illustrate with an example, the relationship between sequence diagram and use cases. (UNIV-
5 TIMES) [16]
2. With a suitable example explain how to design a class. Give all possible representation in a
class. (name, attribute, visibility, methods, responsibilities) [OR] Describe UML notation for
Class diagram with an example. Explain the concept of link, association and inheritance.
(UNIV- 5 TIMES) [16]
5. Explain the logical architecture and UML package diagram. (UNIV- 9 TIME) [16]
_____________________________________________________________________________
SSD needs:
-External events
-Timer events
-Faults/exception
Illustrates input and output events related to the system under discussion.
For the purpose of software development, the system boundary is chosen to be the
software system itself.
System event
System operation
– Strict layered
– Relaxed layered
Typical Layers
• User interface
• In strict layering, a layer only calls upon services in the layer directly below it.
Software Architecture
• Selection of structural elements and their interfaces, along with their behavior.
• The logical architecture is the large-scale organization of the classes into packages
(namespaces), subsystems, and layers.
Reverse-Engineering
• UML case tools is to reverse engineer the source-code and generate a package diagram
automatically.
Package
Nesting
UI Domain
UI
UI::Swing UI::Web
Swing Web
Domain::Sales
Domain
Sales
Layers Benefits
• Logical segmentation.
• GUI
• Business infrastructure
• Tech services
Cohesive Responsibilities
• Lower representation gap between real world domain and software design.
• Tiers were originally logical layers, but now the term has come to mean physical nodes.
• 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
• 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
• No application layer
• Hiding UI objects
• System operations invoked on the system are request generated by an actor via UI layer
onto the application layer.
– All layers deployed within the same process on the same node.
• Interface
• Application logic
• Storage
– Monitoring application
– Simulation application
• +/- visibility,compartments.
• Multiple perspectives
UML Attributes
•
UML Attributes: Attribute Text & Association lines
1. Navigation arrow
4. No association name
• Property string
– {Ordered}/{Ordered,List}
//}
Dependency
• Kinds of dependency,
– Implementation of an interface
– Attributes
Dependency Labels
Interfaces
• Guideline:
Qualified Association
Association class
• It treats association itself as a class & model it with attributes, operation & other features.
Singleton classes
• Class can be marked with a ‘1’ in the upper right corner of the compartment
Active class
• Shown with double vertical lines on left & right side of class box
Types:
– Sequence diagram
Sequence Diagram
Communication Diagram
– Actual lifelines
– Dashed ->UML
– Solid/dashed ->UML2
• Messages
– Actual lifelines
– Dashed ->UML
– Solid/dashed ->UML2
• Messages
• Message syntax
– Return var=message(parameter)
• Getdate--
• -- adate
Creation of Instances
Diagram frames
Frame formats
Frame Meaning
operator
region Critical regions within which only one thread can run
SD notation
• Conditional message :
Nesting of frames
Interaction diagrams
• Asynchronous message
– doesn’t block
– Filled arrow.
• Links
– Instance of an association
Message to “self” or
“this”
Instance creation
Conditional messages
Iteration or looping
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.
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.
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.
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 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.
3.Class Testing
5.GUI Testing
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.
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).
ProductDescription
SalesLineItem
description description : Text
quantity : Integer price : Money
1 itemID : ItemID
getSubtotal() : Money
...
{
ProductDescription desc = catalog.ProductDescription(id);
currentSale.makeLineItem(desc, qty);
}
1: desc := getProductDescription(id)
:Product
Catalog
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()
{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(...)
enterItem(...) getSubtotal()
makePayment(...)
makeNewSale()
getTotal()
makePayment(...)
...
1
* Payment
amount : Money
1
...
• 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.
Hence to define an object – oriented unit as the work of one person, which ends up
as a set of class operations.
Example:
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.
• 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
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.
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
__________________________________________________________________
2.CLASS TESTING
A unit is a
o Is a smallest chunk that can be compiled by itself
o A single procedure/function
o 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
– Month
– Year
CRC - Class Responsibility Cards for each class.
Class: CalendarUnit
Class: testIt
Class: Date
Classes as units
3 views of a class:
• Static class
• Compile-time view
• Execution time view
Levels of Testing
Requirements System
Specification T esting
Preliminary Integration
Design T esting
Detailed
Unit
Design
T esting
Coding
After this level, integration level details are added. Collaboration diagram shows
message traffic among classes
Top-Down
Bottom-Up
Sandwich
Big Bang
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.
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.
Start with ultra-center and add nodes that are one edge away, then add nodes that
are 2 edges away and so on..
Sequence diagram
-Class level
Sequence diagram traces execution time path .Serve as basis for integration testing.
----------------------------------------------------------------------------------------------------
• Method/Message path
• MM-path starts with a method and ends when it reaches a method that does
not issue any messages of its own.
-------
--
------------------------------------------------------------------------------------------------
Data can get values from inheritance tree.Data can be defined at various stages of
message passing.Program graphs are formed
Definition
petrinet
4.GUI TESTING
• Test a GUI application – begin with user input events and all system output
events.
Example
High level complete view of application. State are external appearances of GUI.
Methods: Concentrates all logic in one place and simply uses the status of
the option buttons as conditions in IF test
Second – more object oriented – have methods in each option button object.
Event driven petri nets to describe threads to be tested.Port i/p and o/p
events in currency conversion GUI.
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.
System level threads are built by composing atomic system function into
sequence.
T1=<s1,s4,s6,s7>
T2=<s1,s2,s6,s7>
T3=<s3,s1,s6,s8>
T4=<s5,s1,s7,s8>
Set T constitutes minimum level of system testing for the currency conversion
GUI.
------------------------------------------------------------------------------------------------
SYSTEM TESTING:
• Port Input
• Output events.
project Inception
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.
Expanded EUC
Real Usecases :
There are four identifiable levels with corresponding coverage metrics for
GUI applications.
Two of these are dependent on UML specification.
Level 1
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: