0% found this document useful (0 votes)
59 views49 pages

00000004-Ooad Unit-5

The document covers key concepts in modeling events, signals, state machines, processes, and threads, emphasizing their roles in system design. It details various types of events, including signal and call events, and explains state machine components such as states, transitions, and actions. Additionally, it discusses modeling techniques for synchronization, timing constraints, and the distribution of objects within a system.

Uploaded by

sreevs749
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
59 views49 pages

00000004-Ooad Unit-5

The document covers key concepts in modeling events, signals, state machines, processes, and threads, emphasizing their roles in system design. It details various types of events, including signal and call events, and explains state machine components such as states, transitions, and actions. Additionally, it discusses modeling techniques for synchronization, timing constraints, and the distribution of objects within a system.

Uploaded by

sreevs749
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 49

UNIT-V

Events and signals, state machines, processes and threads, time and space.
State chart diagrams, component diagrams, deployment diagrams.

Events and signals


• An event is the specification of a significant occurrence that has a location in time and space.
• In the context of state machines, an event is an occurrence of a stimulus that can trigger a state
transition.
• A signal is a kind of event that represents the specification of an asynchronous stimulus
communicated between instances.

Kinds of Events
• Events may be external or internal. External events are those that pass between the system and its
actors.
• For example, the pushing of a button and an interrupt from a collision sensor are both examples
of external events.
• Internal events are those that pass among the objects that live inside the system. An overflow
exception is an example of an internal event.
1. Signal Event
• A signal event represents a named object that is dispatched (thrown) asynchronously by one
object and then received (caught) by another. Exceptions are an example of internal signal.
• A signal event is an asynchronous event
• Signal events may have instances, generalization relationships, attributes and operations.
Attributes of a signal serve as its parameters.
• A signal event may be sent as the action of a state transition in a state machine or the sending of
a message in an interaction.
• Signals are modeled as stereotyped classes and the relationship between an operation and the
events by using a dependency relationship, stereotyped as send.

Fig: Signals

2. Call Events
• Just as a signal event represents the occurrence of a signal, a call event represents the dispatch of
an operation.
• Whereas a signal is an asynchronous event, a call event is, in general, synchronous.
• It means when an object invokes an operation on another object that has a state machine, control
passes from the sender to the receiver, the transition is triggered by the event, the operation is
completed, the receiver transitions to a new state, and control returns to the sender.

3. Time and Change Events


• A time event is an event that represents the passage of time. In the UML you model a time event
by using the keyword after followed by some expression that evaluates to a period of time.
• A change event is an event that represents a change in state or the satisfaction of some condition.
In the UML you model a change event by using the keyword when followed by some Boolean
expression.
4. Sending and Receiving Events
• Signal events and call events involve at least two objects: the object that sends the signal or
invokes the operation, and the object to which the event is directed.
• Signals are asynchronous, and asynchronous calls are themselves signals, the semantics of events
interact with the semantics of active objects and passive objects.

Common Modeling Techniques

1. Modeling a Family of Signals


To model a family of signals,
• Consider all the different kinds of signals to which a given set of active objects may respond.
• Look for the common kinds of signals and place them in a generalization/specialization hierarchy
using inheritance.
• Look for the opportunity for polymorphism in the state machines of these active objects.
2. Modeling Exceptions
• For each class and interface, and for each operation of such elements, consider the exceptional
conditions that may be raised.
• Arrange these exceptions in a hierarchy. Elevate general ones, lower specialized ones, and
introduce intermediate exceptions, as necessary.
• For each operation, specify the exceptions that it may raise. You can do so explicitly (by showing
send dependencies from an operation to its exceptions) or you can put this in the operation's
specification.

State Machines

Terms and Concepts


• A state machine is a behavior that specifies the sequences of states an object goes through during
its lifetime in response to events, together with its responses to those events.
• A state is a condition or situation during the life of an object during which it satisfies some
condition, performs some activity, or waits for some event.

States
A state is a condition or situation during the life of an object during which it satisfies some condition,
performs some activity, or waits for some event. An object remains in a state for a finite amount of time.
A state has several parts.
Name A textual string that distinguishes the state from other states; a state may
be anonymous, meaning that it has no name

Entry/exit actions Actions executed on entering and exiting the state, respectively

Internal Transitions Transitions that are handled without causing a change in state

Substates The nested structure of a state, involving disjoint (sequentially active) or


concurrent (concurrently active) substates

Deferred A list of events that are not handled in that state but, rather, are
events postponed and queued for handling by the object in another state

Initial and Final States


Figure shows, there are two special states that may be defined for an object's state machine.
First, there's the initial state, which indicates the default starting place for the state machine or substate.
An initial state is represented as a filled black circle.
Second, there's the final state, which indicates that the execution of the state machine or the enclosing
state has been completed. A final state is represented as a filled black circle surrounded by an unfilled
circle.

Transitions
A transition is a relationship between two states indicating that an object in the first state will perform
certain actions and enter the second state when a specified event occurs and specified conditions are
satisfied. A transition has five parts.

Source state The state affected by the transition; if an object is in the source state, an outgoing
transition may fire when the object receives the trigger event of the transition and if the
guard condition, if any, is satisfied

Event The event whose reception by the object in the source state makes the transition
trigger eligible to fire, providing its guard condition is satisfied
Guard A Boolean expression that is evaluated when the transition is triggered by the reception
condition of the event trigger; if the expression evaluates True, the transition is eligible to fire; if
the expression evaluates False, the transition does not fire and if there is no other
transition that could be triggered by that same event, the event is Lost

Action An executable atomic computation that may directly act on the object that owns the
state machine, and indirectly on other objects that are visible to the object

Target The state that is active after the completion of the transition
state

Event Trigger
• An event is the specification of a significant occurrence that has a location in time and space. An
event is an occurrence of a stimulus that can trigger a state transition.
• A signal or a call may have parameters whose values are available to the transition, including
expressions for the guard condition and action.
Guard
• A guard condition is rendered as a Boolean expression enclosed in square brackets and placed
after the trigger event.
• A guard condition is evaluated only after the trigger event for its transition occurs.
Action
• An action is an executable atomic computation. Actions may include operation calls the creation
or destruction of another object, or the sending of a signal to an object.
Common Modeling Techniques

1. Modeling the Lifetime of an Object

• Set the context for the state machine, whether it is a class, a use case, or the system as a whole.
• Establish the initial and final states for the object. To guide the rest of your model, possibly
state the pre- and postconditions of the initial and final states, respectively.
• Decide on the events to which this object may respond.
• Starting from the initial state to the final state, lay out the top-level states the object may be in.
Connect these states with transitions triggered by the appropriate events. Continue by adding
actions to these transitions.
• Identify any entry or exit actions (especially if you find that the idiom they cover is used in the
state machine).
• Expand these states as necessary by using substates.
• Check that all actions mentioned in the state machine are sustained by the relationships,
methods, and operations of the enclosing object.
• Check that all actions mentioned in the state machine are sustained by the relationships,
methods, and operations of the enclosing object.
• Trace through the state machine, either manually or by using tools, to check it against
expected sequences of events and their responses. Be especially diligent in looking for
unreachable states and states in which the machine may get stuck.
• After rearranging your state machine, check it against expected sequences again to ensure that
you have not changed the object's semantics.

Processes and Threads

Terms and Concepts


• A process is a heavyweight flow that can execute concurrently with other processes.
• A thread is a lightweight flow that can execute concurrently with other threads within the same
process.
• An active object is an object that owns a process or thread and can initiate control activity.
• Processes and threads are rendered as stereotyped active classes.
• An active class is a class whose instances are active objects.
Flow of Control
• In a sequential system, there is a single flow of control. i.e, one thing, and one thing only, can
take place at a time.
In a concurrent system, there is multiple simultaneous flow of control i.e, more than one thing
can take place at a time.

Classes and Events

• Active classes are just classes which represents an independent flow of control
• Active classes share the same properties as all other classes.
• When an active object is created, the associated flow of control is started; when the active object
is destroyed, the associated flow of control is terminated
• two standard stereotypes that apply to active classes are, <<process>> – Specifies a heavyweight
flow that can execute concurrently with other processes. (heavyweight means, a thing known to
the OS itself and runs in an independent address space) <<thread>> – Specifies a lightweight
flow that can execute concurrently with other threads within the same process (lightweight
means, known to the OS itself.)
• All the threads that live in the context of a process are peers of one another.

Communication
• In a system with both active and passive objects, there are four possible combinations of
interaction.
• First, a message may be passed from one passive object to another.
• Second, a message may be passed from one active object to another.
• In inter-process communication there are two possible styles of communication. First, one active
object might synchronously call an operation of another. Second, one active object might
asynchronously send a signal or call an operation of another object.
• a synchronous message is rendered as a full arrow and an asynchronous message is rendered as a
half arrow.
• Third, a message may be passed from an active object to a passive object.
• Fourth, a message may be passed from a passive object to an active one.

Synchronization
• Synchronization means arranging the flow of controls of objects so that mutual exclusion will
be guaranteed.
• Three approaches are there to handle synchronization:
• Sequential – Callers must coordinate outside the object so that only one flow is in the object at a
time
• Guarded – multiple flow of control is sequentialized with the help of object‘s guarded operations.
in effect it becomes sequential.
• Concurrent – multiple flow of control is guaranteed by treating each operation as atomic
• synchronization are rendered in the operations of active classes with the help of constraints
Common Modeling Techniques

1. Modeling Multiple Flows of Control

• Identify the opportunities for concurrent action and vreify each flow as an active class. Generalize
common sets of active objects into an active class.
• Capture these static decisions in class diagrams, explicitly highlighting each active class.
• Capture these static decisions in class diagrams, explicitly highlighting each active class.
• Consider how each group of classes collaborates with one another dynamically. Capture those
decisions in interaction diagrams. Explicitly show active objects as the root of such flows.
• Identify each related sequence by identifying it with the name of the active object. Pay close
attention to communication among active objects. Apply synchronous and asynchronous
messaging, as appropriate.
• Pay close attention to synchronization among these active objects and the passive objects with
which they collaborate. Apply sequential, guarded, or concurrent operation semantics, as
appropriate.

2. Modeling Interprocess Communication

• Model the multiple flows of control.


• Consider which of these active objects represent processes and which represent threads.
• Model messaging using asynchronous communication. model remote procedure calls using
synchronous communication.
• Informally specify the underlying mechanism for communication by using notes, or more
formally by using collaborations.
Time and Space

Terms and Concepts


• A time expression is an expression that evaluates to an absolute or relative value of time.
• A timing constraint is a semantic statement about the relative or absolute value of time.
Graphically, a timing constraint is rendered as for any constraint.
• Location is the placement of a component on a node. Graphically, location is rendered as a tagged
value.

Time
• Real time systems are, by their very name, time-critical systems.
• Events may happen at regular or irregular times; the response to an event must happen at
predictable absolute times or at predictable times relative to the event itself.
• The passing of messages represents the dynamic aspect of any system, so when you model the
time-critical nature of a system with the UML, you can give a name to each message in an
interaction to be used as a timing mark

Common Modeling Techniques

1. Modeling Timing Constraints

• For each event in an interaction, consider whether it must start at some absolute time. Model
that real time property as a timing constraint on the message.
• For each interesting sequence of messages in an interaction, consider whether there is an
associated maximum relative time for that sequence. Model that real time property as a timing
constraint on the sequence.
• For each time critical operation in each class, consider its time complexity. Model those
semantics as timing constraints on the operation
2. Modeling the Distribution of Objects

• For each interesting class of objects in your system, consider its locality of reference. In other
words, consider all its neighbors and their locations. A tightly coupled locality will have
neighboring objects close by
• Next consider patterns of interaction among related sets of objects. Co-locate sets of objects that
have high degrees of interaction, to reduce the cost of communication. Partition sets of objects
that have low degrees of interaction.
• Next consider the distribution of responsibilities across the system. Redistribute your objects to
balance the load of each node.
• Consider also issues of security, volatility, and quality of service, and redistribute your objects as
appropriate.
3. Modeling Objects that Migrate

• Select an underlying mechanism for physically transporting objects across nodes.


• Render the allocation of an object to a node by explicitly indicating its location as a tagged value.
• Using the become and copy stereotyped messages, render the allocation of an object to a new
node.
• Consider the issues of synchronization (keeping the state of cloned objects consistent) and
identity (preserving the name of the object as it moves).

Statechart Diagrams

Terms and Concepts


• A statechart diagram shows a state machine, emphasizing the flow of control from state to state.
• A state machine is a behavior that specifies the sequences of states an object goes through during
its lifetime in response to events, together with its responses to those events.
• A state is a condition or situation in the life of an object during which it satisfies some condition,
performs some activity, or waits for some event.

Contents - Statechart diagrams commonly contain

 Simple states and composite states


 Transitions, including events and actions
• A statechart diagram is basically a projection of the elements found in a state machine.
• statechart diagrams contain branches, forks, joins, action states, activity states, objects, initial
states, final states, history states.
Common uses
• A statechart diagram will use to model some dynamic aspect of a system.
• It is also used in the context of virtually any modeling element.
• Typically, use statechart diagrams in the context of the system as a whole, a subsystem, or a class.
• It can also be used to attach a statechart diagrams to use cases.

Common Modeling Technique

1. Modeling Reactive Objects - To model a reactive object,

• Choose the context for the state machine, whether it is a class, a use case, or the system as a
whole.
• Choose the initial and final states for the object. To guide the rest of your model, possibly state
the pre- and postconditions of the initial and final states, respectively.
• Decide on the stable states of the object by considering the conditions in which the object may
exist for some identifiable period of time. Start with the high-level states of the object and only
then consider its possible substates.
• Decide on the meaningful partial ordering of stable states over the lifetime of the object.
• Decide on the events that may trigger a transition from state to state. Model these events as
triggers to transitions that move from one legal ordering of states to another.
• Attach actions to these transitions (as in a Mealy machine) and/or to these states (as in a Moore
machine).
• Consider ways to simplify your machine by using substates, branches, forks, joins, and history
states.
Fig: Modeling Reactive Objects

2. Forward and Reverse Engineering

• Forward engineering(the creation of code from a model) is possible for statechart diagrams,
especially if the context of the diagram is a class.
• The forward engineering tool must generate the necessary private attributes and final static
constants.
• Reverse engineering (the creation of a model from code) is theoretically possible, but practically
not very useful. The choice of what constitutes a meaningful state is in the eye of the designer.
• Reverse engineering tools have no capacity for abstraction and therefore cannot automatically
produce meaningful statechart diagrams.
A well-structured statechart diagram

• Is focused on communicating one aspect of a system's dynamics.


• Contains only those elements that are essential to understanding that aspect.
• Provides detail consistent with its level of abstraction (expose only those features that are essential to
understanding).
• Uses a balance between the styles of Mealy and Moore machines.

When you draw a statechart diagram

• Give it a name that communicates its purpose.


• Start with modeling the stable states of the object, then follow with modeling the legal transitions
from state to state. Address branching, concurrency, and object flow as secondary considerations,
possibly in separate diagrams.
• Lay out its elements to minimize lines that cross.

Component

• A component is a physical and replaceable part of a system that conforms to and provides the
realization of a set of interfaces. Graphically, a component is rendered as a rectangle with tabs.
Names
• A component name must be unique within its enclosing package

Components and Classes


• There are some significant differences between components and classes.
• Classes represent logical abstractions; components represent physical things that live in the world
of bits. In short, components may live on nodes, classes may not.
• Components represent the physical packaging of otherwise logical components and are at a
different level of abstraction.
• Classes may have attributes and operations directly. In general, components only have operations
that are reachable only through their interfaces.
Components and Interfaces

• An interface is a collection of operations that are used to specify a service of a class or a


component. The relationship between component and interface is important. All the most
common component-based operating system facilities (such as COM+, CORBA, and Enterprise
Java Beans) use interfaces as the glue that binds components together.
• An interface that a component realizes is called an export interface, meaning an interface that the
component provides as a service to other components. A component may provide many export
interfaces.
• The interface that a component uses is called an import interface, meaning an interface that the
component conforms to and so builds on.
• A component may conform to many import interfaces.
• A component may both import and export interfaces.

Binary Replaceability

• The basic intent of every component-based operating system facility is to permit the assembly of
systems from binary replaceable parts.
• This means that you can create a system out of components and then evolve that system by
adding new components and replacing old ones, without rebuilding the system.
• Interfaces are the key to making this happen. When you specify an interface, you can drop into
the executable system any component that conforms to or provides that interface.
• You can extend the system by making the components provide new services through other
interfaces, which, in turn, other components can discover and use. These semantics explain the
intent behind the definition of components in the UML.

Kinds of Components

Three kinds of components may be distinguished


• First, there are deployment components.
• Second, there are work product components.
• Third are execution components.

Organizing Components
• You can organize components by grouping them in packages in the same manner in which you
organize classes.
• The UML defines five standard stereotypes that apply to components

1. executable
2. library
3. table
4. file
5. document

Common Modeling Techniques

1. Modeling Executables and Libraries


To model executables and libraries:

• Identify the partitioning of your physical system. Consider the impact of technical, configuration
management, and reuse issues.
• Model any executables and libraries as components, using the appropriate standard elements. If
your implementation introduces new kinds of components, introduce a new appropriate
stereotype.
• If it's important for you to manage the seams in your system, model the significant interfaces that
some components use and others realize.
• As necessary to communicate your intent, model the relationships among these executables,
libraries, and interfaces. Most often, you'll want to model the dependencies among these parts in
order to visualize the impact of change.
2. Modeling Tables, Files, and Documents
To model tables, files, and documents,

• Identify the ancillary components that are part of the physical implementation of your system.
• Model these things as components. If your implementation introduces new kinds of artifacts,
introduce a new appropriate stereotype.
• As necessary to communicate your intent, model the relationships among these ancillary
components and the other executables, libraries, and interfaces in your system.
• Most often, you'll want to model the dependencies among these parts in order to visualize the
impact of change.

3. Modeling an API
To model an API,
• Identify the programmatic seams in your system and model each seam as an interface, collecting
the attributes and operations that form this edge.
• Expose only those properties of the interface that are important to visualize in the given context;
otherwise, hide these properties, keeping them in the interface's specification for reference, as
necessary.
• Model the realization of each API only insofar as it is important to show the configuration of a
specific implementation.
4. Modeling Source Code
To model source code,

• Depending on the constraints imposed by your development tools, model the files used to store
the details of all your logical elements, along with their compilation dependencies.
• If it's important for you to bolt these models to your configuration management and version
control tools, you'll want to include tagged values, such as version, author, and check in/check out
information, for each file that's under configuration management.
• As far as possible, let your development tools manage the relationships among these files, and use
the UML only to visualize and document these relationships.

Component Diagrams

• A component diagram shows a set of components and their relationships. Graphically, a


component diagram is a collection of vertices and arcs.

Contents
Component diagrams commonly contain
• Components
• Interfaces
• Dependency, generalization, association, and realization relationships Like all other diagrams,
component diagrams may contain notes and constraints.

Common uses
• Component diagrams used to model the static implementation view of a system.
• Typically use component diagrams in one of four ways.
1. To model source code
2. To model executable releases
3. To model physical databases
4. To model adaptable systems

Common Modeling Techniques

1. Modeling Source Code


To model a system's source code:

• Either by forward or reverse engineering, identify the set of source code files of interest and
model them as components stereotyped as files.
• For larger systems, use packages to show groups of source code files.
• Consider exposing a tagged value indicating such information as the version number of the source
code file, its author, and the date it was last changed. Use tools to manage the value of this tag.
• Model the compilation dependencies among these files using dependencies. Again, use tools to
help generate and manage these dependencies.

2. Modeling an Executable Release


To model an executable release
• Identify the set of components you'd like to model. Typically, this will involve some or all the
components that live on one node, or the distribution of these sets of components across all the
nodes in the system.
• Consider the stereotype of each component in this set. For most systems, you'll find a small
number of different kinds of components (such as executables, libraries, tables, files, and
documents). You can use the UML's extensibility mechanisms to provide visual cues for these
stereotypes.
• For each component in this set, consider its relationship to its neighbors. Most often, this will
involve interfaces that are exported (realized) by certain components and then imported (used) by
others. If you want to expose the seams in your system, model these interfaces explicitly. If you
want your model at a higher level of abstraction, elide these relationships by showing only
dependencies among the components.

3. Modeling a Physical Database


To model a physical database:

• Identify the classes in your model that represent your logical database schema.
• Select a strategy for mapping these classes to tables. You will also want to consider the physical
distribution of your databases. Your mapping strategy will be affected by the location in which
you want your data to live on your deployed system.
• To visualize, specify, construct, and document your mapping, create a component diagram that
contains components stereotyped as tables.
• Where possible, use tools to help you transform your logical design into a physical design.
4. Modeling Adaptable Systems
• Consider the physical distribution of the components that may migrate from node to node. You
can specify the location of a component instance by marking it with a location tagged value,
which you can then render in a component diagram (although, technically speaking, a diagram
that contains only instances is an object diagram).
• If you want to model the actions that cause a component to migrate, create a corresponding
interaction diagram that contains component instances. You can illustrate a change of location by
drawing the same instance more than once, but with different values for its location tagged value.

5. Forward and Reverse Engineering


To forward engineer a component diagram:

• For each component, identify the classes or collaborations that the component implements.
• Choose the target for each component. Your choice is basically between source code (a form that
can be manipulated by development tools) or a binary library or executable (a form that can be
dropped into a running system).
• Use tools to forward engineer your models.

To reverse engineer a component diagram,


• Choose the target you want to reverse engineer. Source code can be reverse engineered to
components and then classes. Binary libraries can be reverse engineered to uncover their
interfaces. Executables can be reverse engineered the least.
• Using a tool, point to the code you'd like to reverse engineer. Use your tool to generate a new
model or to modify an existing one that was previously forward engineered.
• Using your tool, create a component diagram by querying the model. For example, you might
start with one or more components, then expand the diagram by following relationships or
neighboring components. Expose or hide the details of the contents of this component diagram as
necessary to communicate your intent.

Deployment

• A node is a physical element that exists at run time and represents a computational resource,
generally having at least some memory and, often, processing capability. Graphically, a node is
rendered as a cube.
• Every node must have a name that distinguishes it from other nodes.
• A name is a textual string. That name alone is known as a simple name; a path name is the node
name prefixed by the name of the package in which that node lives.
• A node is typically drawn showing only its name, as in. Just as with classes, you may draw nodes
adorned with tagged values or with additional compartments to expose their details.

Nodes and Components


There are some significant differences between nodes and components.
• Components are things that participate in the execution of a system; nodes are things that execute
components.
• Components represent the physical packaging of otherwise logical elements; nodes represent the
physical deployment of components.
Connections

• The most common kind of relationship you'll use among nodes is an association. In this context,
an association represents a physical connection among nodes, such as an Ethernet connection, a
serial line, or a shared bus, as Figure .

Common Modeling Techniques

1. Modeling Processors and Devices


To model processors and devices:

• Identify the computational elements of your system's deployment view and model each as a node.
• If these elements represent generic processors and devices, then stereotype them as such. If they
are kinds of processors and devices that are part of the vocabulary of your domain, then specify
an appropriate stereotype with an icon for each.
• As with class modeling, consider the attributes and operations that might apply to each node.

2. Modeling the Distribution of Components


To model the distribution of components:
• For each significant component in your system, allocate it to a given node.
• Consider duplicate locations for components. It's not uncommon for the same kind of component
(such as specific executables and libraries) to reside on multiple nodes simultaneously.
• Render this allocation in one of three ways.
• Don't make the allocation visible, but leave it as part of the backplane of your model• that is, in
each node's specification.
• Using dependency relationships, connect each node with the components it deploys.
• List the components deployed on a node in an additional compartment.

Deployment Diagrams

A deployment is a diagram that shows the configuration of run time processing nodes and the components
that live on them. Graphically, a deployment diagram is a collection of vertices and arcs.

Contents
Deployment diagrams commonly contain
• Nodes
• Dependency and association relationships
Like all other diagrams, deployment diagrams may contain notes and constraints

Common Uses

When you model the static deployment view of a system, you'll typically use deployment diagrams in one
of three ways.
1. To model embedded systems 2. To model client/server systems 3. To model fully distributed
systems

Common Modeling Techniques


1. Modeling an Embedded System

To model an embedded system:


• Identify the devices and nodes that are unique to your system.
• Provide visual cues, especially for unusual devices, by using the UML's extensibility mechanisms
to define system-specific stereotypes with appropriate icons. At the very least, you'll want to
distinguish processors (which contain software components) and devices (which, at that level of
abstraction, don't directly contain software).
• Model the relationships among these processors and devices in a deployment diagram. Similarly,
specify the relationship between the components in your system's implementation view and the
nodes in your system's deployment view.
• As necessary, expand on any intelligent devices by modeling their structure with a more detailed
deployment diagram
2. Modeling a Client/Server System
To model a client/server system:

• Identify the nodes that represent your system's client and server processors.
• Highlight those devices that are germane to the behavior of your system. For example, you'll want
to model special devices, such as credit card readers, badge readers, and display devices other
than monitors, because their placement in the system's hardware topology are likely to be
architecturally significant.
• Provide visual cues for these processors and devices via stereotyping.
• Model the topology of these nodes in a deployment diagram. Similarly, specify the relationship
between the components in your system's implementation view and the nodes in your system's
deployment view.

3. Modeling a Fully Distributed System


To model a fully distributed system:

• Identify the system's devices and processors as for simpler client/server systems.
• If you need to reason about the performance of the system's network or the impact of changes to
the network, be sure to model these communication devices to the level of detail sufficient to
make these assessments.
• Pay close attention to logical groupings of nodes, which you can specify by using packages.
• Model these devices and processors using deployment diagrams. Where possible, use tools that
discover the topology of your system by walking your system's network.
• If you need to focus on the dynamics of your system, introduce use case diagrams to specify the
kinds of behavior you are interested in, and expand on these use cases with interaction diagrams.

4. Forward and Reverse Engineering


To reverse engineer a deployment diagram:

• Choose the target that you want to reverse engineer. In some cases, you'll want to sweep across
your entire network; in others, you can limit your search.
• Choose also the fidelity of your reverse engineering. In some cases, it's sufficient to reverse
engineer just to the level of all the system's processors; in others, you'll want to reverse engineer
the system's networking peripherals, as well.
• Use a tool that walks across your system, discovering its hardware topology. Record that
topology in a deployment model.
• Along the way, you can use similar tools to discover the components that live on each node,
which you can also record in a deployment model. You'll want to use an intelligent search, for
even a basic personal computer can contain gigabytes of components, many of which may not be
relevant to your system.
• Using your modeling tools, create a deployment diagram by querying the model. For example,
you might start with visualizing the basic client/server topology, then expand on the diagram by
populating certain nodes with components of interest that live on them. Expose or hide the details
of the contents of this deployment diagram as necessary to communicate your intent.
UNIT- IV: GRASP: Designing objects with responsibilities, creator, information expert, low coupling,
high cohesion, Design patterns, creational, factory method, structural, bridge, adaptor, behavioral,
strategy.

GRASP INTRODUCTION

What is Pattern?

It is common that when experts works on particular problems, they need not reinvent the wheel i.e. they
need not find a complete new solution that is completely different from existing solutions. Rather they
remember the similar problem and it solution and reuse the core of it for solving new problem. They think
in terms of ―Problem Solution‖ pairs. Abstracting from such pairs and churning out the commonalities
leads to patterns.

Each pattern is three-part rule which expresses a relation between a certain context, a problem and a
solution.

Patterns have names and they facilitate communication- common vocabulary and understanding-easy to
remember whole concept in a nutshell.

GRASP:
Craig Larman coined these terms for the first time.
stands for General Responsibility Assignment Software Patterns.
The mnemonic meaning could be ―successful OOAD (Object Oriented Analysis & Design) requires
grasping (understanding)‖.
General: = Abstract i.e. widely applicable for variety of situations
Responsibility: = Obligations, duties –information object performing duty of holding information,
computational object performing duty of computation
Assignment: = Giving a responsibility to a module- capability to carry out responsibility
structure and methods
Software: = Computer code
Patterns: = Regularities, templates, abstraction
Assigning responsibilities to objects is always is major task in designing the software’s. Specifically it’s
always a challenge to decide which object carry out what job (responsibilities) and quality of software
design largely depended upon such responsibilities assignment.
Poor choices about such responsibities leads to fragile systems and components which are hard to
maintain, understand, reuse or extend.
Let’s define responsibility:
Responsibility is definedas a contract or obligation of a type or class and is related to behavior.
There are 2 types of responsibilities
 Knowing - responsibilities of an object include
Knowing about private encapsulated data-member data
Knowing about related objects
Knowing about things it can derive or calculate
 Doing - responsibility of an object include
Doing something itself-assign, calculate, create
Initiating action in other objects
Controlling and coordinating activities in other objects

The responsibilities would be translated into classes and their methods and it is largely influenced by the
granularity of the responsibility. Don’t confuse the responsibility as a method in a class even though they
are implemented using methods which either act alone or collaborate with other methods and objects.
Object-oriented principles are applied by experienced developers/experts in deciding general assignment
of responsibilities.
GRASP patterns describe fundamental principles of assigning responsibilities to objects and it has
following principles and patterns in the family

 Information Expert
 Creator
 Controller
 Low Coupling
 High Cohesion
 Polymorphism
 Pure Fabrication
 Indirection
 Protected Variations.
Creator
The main Objective is:
To understand the GRASP pattern ―Creator‖. Problem:

Who creates the new instance of some class?

Solution:
Assign class A the responsibility to create an instance of class B if….
 A aggregates (whole-part relationship) B objects
 A contains B objects
 A records instances of B objects
 A closely uses B objects

 A has initializing data that is needed while creating B objects (thus A is an expert with
respect to creating B)

Approach:

Step I: Closely look at domain/ design model and ask: who should be creating these classes?
Step II: Search for the classes who create, aggregate etc.
Step III: Assign the responsibility of creation

Description
Let’s extend an example of POS (Point Of Sale) systems explained in previous part. This is what we
come across malls where there are many POS counters. In the domain model, following classes are
identified. These classes are shown in the left part of diagram (Fig. No.1). A class ―Register‖ represents
the sales register. This would have details of all sales done. As the ―Register‖ aggregates the ―Sale‖, it
fulfils the first criteria of the solution. Similarly the ―Sale‖ contains the ―SaleLineItem‖. Hence
―Register‖ should create the instance of ―Sale‖ and ―Sale‖ should create instance of ―SaleLineItem‖. Fig.
No. 1
Fig. No. 1

91
Class Relationship with other classes Responsibility and method
Register Contains Class ―Sale‖ Creating an instance createSale()
Sale Composite aggregation with Creating an instance
SaleLineItem makeSaleLineItem()

Following diagram depicts the assignment of responsibilities and corresponding methods. Fig No. 2

Fig No. 2

Benefits:
 Support low coupling

 The responsibility is assigned to a class which fulfils the criteria thus separating the logic for
creation and actual execution.

Liabilities /Contradictions:

 Sometimes creation may require significant complexity. Many a times there would be tight
coupling among the creator and create class. Also the task of destroying the objects is to be
thought of. Recycling of such instances (pooling) becomes important for the performance reasons.

 In many scenarios the creations is conditional and it may be from family of classes making it very
complex.

 For creation of family of classes or to tackle the creation and recycling, other patterns are available
which are factory, abstract factory etc.

Information Expert
Objective
To understand about the GRASP pattern ―Information Expert’.

Problem: Any real world application has hundreds of classes and thousand of actions. How do I start
assigning the responsibility?

92
Solution: Assign a responsibility to Information Expert, the class that has information necessary to fulfil
the responsibility.‖
Generally, if domain model is ready then it is pretty straight forward to assign the responsibilities and
arrive at design model.
Approach
Step I: State the responsibility clearly.
Step II: Search for the classes who have the information needed to fulfil the responsibility.
Step III: Assign the responsibility

Description
Let’s take an example of POS (Point Of Sale) systems. This is what we come across malls where there are
many POS counters. In the domain model, following classes are identified. These classes are shown in the
left part of diagram (Fig. No.1). Let’s think about some responsibility.

Who should have the responsibility of calculating the Sales Total?


Sales Total =Sum of (Unit price X quantity of sale line item)
E.g. a person is buying 2 line items, toothpaste (2 no’s) and soap (2 no’s) are being bought Sales total =
(Price of toothpaste)* (quantity of toothpaste) + (Price of soap)* (quantity of soap)

93
In the above scenario, the classes Sale, ―SaleLineItem‖ and ―ProductSpecification‖ has the
information such as unit price for item/ product (―ProductSpecification‖), sales quantity
(―SaleLineItem‖) and no. of saleLineItems (―Sale‖). So the responsibility of arriving at Sales Total needs
to be assigned to all these classes. Now in this case, If the class is encapsulating data members then
maintaining these data values is the responsibility of the class and it should provide the get and set
methods for accessing such data.

Class Data Values Encapsulated Responsibility and method


ProductDescription UnitPrice Getting the unit price getPrice()
SaleLineItem Quantity of items and hence the Getting the Subtotal getSubTotal()
subtotal for particular item
Quantity X Unit Price
Sale No. of Saleline Items, data and Get the Total of Sales getTotal()
time Sumof(getSubTotal()x
SaleLine item )

It is demonstrated in right portion of above diagram (Fig. No.1).


Following diagram depicts the assignment of responsibilities and corresponding methods.

94
Benefits:

 Encapsulation is maintained as objects use their own data to fulfil the task.
 Support low coupling

 Behaviour (responsibility) is distributed across the classes that have the required information thus
encouraging the highly cohesive lightweight classes

Liabilities /Contradictions:

 Sometimes while assigning responsibilities, lower level responsibilities are uncovered e.g what
the profit or loss for a particular sale?

 Not all the times the application of this pattern is desirable. Consider the responsibility of
saving such Sale to database. By the principle for this pattern, it should be the class ―Sale‖ to
carry out this responsibility but as experienced programmer we know it is hardly the case. The
DAL (Data Access Layer) carries out this responsibilities may be by providing methods such as
SaveSale() into some controller class.

95
Low Coupling
Objective
To understand the GRASP pattern ―Low Coupling‖

The principle behind this pattern is “How to support low dependency and increased reuse?” and “How

to assign the responsibilities so that the coupling is low?”


Coupling refers to connectedness or linking. It is a measure of how strongly one class is connected to or
has knowledge (information or knowhow) of or relies/depends upon the other classes. With experience,
programmers would agree on something i.e. making changes is always been the hardest task and given a
chance all would like to work upon systems from ground up. With increased complexity in the
programming world and programming languages, designing is becoming driver for system’s overall
quality and usability. Designing for low connectedness is an important activity which can help to have a
system in such a way that the changes in one element (sub-system, system, class, etc) will limit changes
to other elements. Being at extreme, is it possible to have no coupling at all? The answer to this question
is ―No‖ as without having any connection; a system can’t be called a system.
High coupling (high dependency, linking and connectedness) leads to

 Cascade of changes – this forces changes in related classes

 Harder to reuse its use of highly coupled elements requires the additional presence of the
classes it is dependent on
 Harder to understand in isolation

Problem: How to reduce impact of changes and encourage reuse?


Solution: Assign a responsibility so that the coupling (linking classes) remains low

Approach:
Step I: Closely look for classes with many associations to other classes.

Step II: Look for the methods that rely on a lot of other methods (or methods in other classes i.e.
dependencies
Step III: Rework the design so as assign responsibilities to different classes in such a way that
they have lesser association and dependency.

96
Description
Let’s extend an example of POS (Point Of Sale) systems carried in series of articles. In the domain model,
following classes like Register, Payment and Sale are identified. These classes are shown in the left part
of diagram (Fig. No.1). There are many system operations such as closing a sale, make payment etc
which are related to business function ―Sales‖.
Fig No. 1

97
Class Relationship with other Responsibility and Remarks
classes method
―Register‖ of Design Creator of the ―Payment‖ Controls and coordinates the So if Sale or payment
I Controls the ―Sale‖ sale through makePayment() changes its going to
affect the Register.
This results in tight
Coupling
Register‖ and ―Sale‖ Controller of ―Sale‖ and Creating an instance This results in
of Design II ―Sale‖ being the creator ―create‖ Controlling the division of
of ―Payment‖ Sale through Responsibilities and
makePayment() Hence low coupling
as ―Register‖ need
not know about the
payment.

The common forms of coupling for A to B include


 A has a data member which refers to B instance
 A has a method which B is an argument
 A is direct or indirect subclass of B
 B is an interface and A implements B

Related Patterns: The pattern related to is ―High Cohesion‖.


Benefits
 Maintainability -Little or not affected by changes in other components
 Understandability- simple to understand in the isolation
 Reusability- convenient to reuse and easier to grab hold of classes

Liabilities / Contradictions:
 Coupling to stable elements (classes in library or well tested classes) doesn’t account to be a
problem.

98
High Cohesion
Objective
To understand the GRASP pattern ―High Cohesion‖
The dictionary meaning of the word ―cohesion‖ is ―the state of cohering or sticking together‖. In
botany world ―the process of some parts (which are generally separate) of plant growing together‖ and in
physics world ―it’s the intermolecular force that holds together the molecules in solid or liquid‖. So this
meaning would give us good forethought as what would ―High Cohesion‖ would mean in the context of
responsibilities? As we have proceeded through this series, we have seen principles behind assigning the
responsibilities. Once they are assigned or being assigned, an important aspect is how they are related or
focused? If they are related, sticking together or focussed, the element carrying to those responsibilities
would become bloated and result into system quite complex and harder to maintain and reuse. The
principle behind this pattern is “How to keep complexity manageable?
Cohesion can be said to a measure of ―relatedness‖ or ―how related all the attributes
and behaviour in a class are‖. High cohesion refers to how strongly relate the responsibilities are.
A class with low cohesion i.e. carrying out the unrelated responsibilities in turn does so many
unrelated things or end up doing too much of a work. Such classes culminates into

 Hard to comprehend or understand


 Harder to reuse as it is tough job to segregate and mark the reusable elements
 Harder to maintain and extend

Problem: How to keep classes focused and manageable?


Solution: Assign responsibility so that cohesion remains high

Approach:

Step I: Closely look for classes with probability of many responsibilities i.e. classes with too-few
or disconnected methods.
Step II: Look for the methods which do a lot (look for method names having words like ―AND‖,
―OR‖)
Step III: Assign a responsibility in such a way that all the responsibilities in a class are
related

99
Description
Let’s extend an example of POS (Point Of Sale) systems carried in series of articles. In the domain model,
following classes like Register, Payment and Sale are identified. In the upper part of diagram (Fig. No.1)
a class ―Register‖ is displayed carrying out many unrelated responsibilities. There are many system
operations such as closing a sale, make payment etc which are related to business function ―Sales‖.
Fig No. 1

100
Class Responsibility and Remarks
Relationship with other method
classes
―Register‖of Creator of the ―Payment‖, Carries out These are absolutely
Design ―Sale‖ and responsibilities for unrelated
I ―SaleLineItem‖ adding sale, payment and responsibilities
also the sale line item. resulting in low
cohesion
―Register‖ Controller of ―Sale‖ and Creating an instance This results in
And ―Sale‖ of ―Sale‖ being the creator ―create‖Controlling the Division of
Design II of ―Payment‖ Sale through responsibilities
makePayment() according to relations
among them and
reduces
the complexity
hence high cohesion
The common examples of Low cohesion are

 System level: ATM having functionality for getting ―Teller Reports‖ i.e. for user this is not
required and related
 Class level: An ―Employee‖ class with a method called ―getDrivingRecords()‖

 Method level: The methods with having ―AND‖,‖OR‖ in their names which implies that the
method is going to execute multiple functions making it difficult to reuse.

 This also applies to subsystem (package), component level. E.g. a component for exception
handling also doing job of caching.

One of the fundamental goals of an effective design is to achieve high cohesion with low coupling.

Larman has described degree of cohesion from low to high


 Very low cohesion:- Class responsible for many things in unrelated areas

 Low cohesion:-Class responsible for many things in related areas

 Moderate cohesion :- Class has few responsibilities in different areas which are related to the
class but not to each other

 High Cohesion- Class has few responsibilities in one area and collaborates with other classes to
fulfill tasks

Related Patterns: This pattern is related rather complementary to ―Low Coupling‖ and little
contradictory to information expert.

101
Benefits

 Understandability :- Clarity and ease of understanding design is increased


 Maintainability :- Maintenance and enhancements are simplified
 Low coupling is often supported

 Reusability :Small size classes with highly related functionality increases reuse

Design Patterns

A design patterns are well-proved solution for solving the specific problem/task.

Now, a question will be arising in your mind what kind of specific problem? Let me explain by taking an
example.

Problem Given:

Suppose you want to create a class for which only a single instance (or object) should be created and that
single object can be used by all other classes.

Solution:
Singleton design pattern is the best solution of above specific problem. So, every design pattern has
some specification or set of rules for solving the problems. What are those specifications, you will see
later in the types of design patterns.

Advantage of design pattern:

 They are reusable in multiple projects.


 They provide the solutions that help to define the system architecture.
 They capture the software engineering experiences.
 They provide transparency to the design of an application.
 They are well-proved and testified solutions since they have been built upon the knowledge and
experience of expert software developers.
 Design patterns don?t guarantee an absolute solution to a problem. They provide clarity to the
system architecture and the possibility of building a better system.

When should we use the design patterns?

We must use the design patterns during the analysis and requirement phase of SDLC(Software
Development Life Cycle).

Design patterns ease the analysis and requirement phase of SDLC by providing information based on
prior hands-on experiences.

102
Categorization of design patterns:

Basically, design patterns are categorized into two parts:

1. Core java (or JSE) Design Patterns.


2. JEE Design Patterns.

Core Java Design Patterns

In core java, there are mainly three types of design patterns, which are further divided into their sub-parts:

 Creational Design Pattern

Factory Pattern
Factory Method Pattern
Abstract Factory Pattern
Singleton Pattern
Prototype Pattern
Builder Pattern.

 Structural Design Pattern


Adapter Pattern
Bridge Pattern
Composite Pattern
Decorator Pattern
Facade Pattern
Flyweight Pattern
Proxy Pattern

 Behavioral Design Pattern

o Chain Of Responsibility Pattern


o Command Pattern
o Interpreter Pattern
o Iterator Pattern
 Mediator Pattern

 Memento Pattern

 Observer Pattern

 State Pattern
103
 Strategy Pattern

 Template Pattern

 Visitor Pattern

Creational Design Pattern

What are creational patterns?

• Design patterns that deal with object creation mechanisms, trying to create objects in a manner
suitable to the situation
• Make a system independent of the way in which objects are created, composed and represented
• Recurring themes:
– Encapsulate knowledge about which concrete classes the system uses (so we can change
them easily later)
– Hide how instances of these classes are created and put together (so we can change it
easily later)

Benefits of creational patterns

• Creational patterns let you program to an interface defined by an abstract class


• That lets you configure a system with ―product‖ objects that vary widely in structure and
functionality
• Example: GUI systems
– InterViews GUI class library
– Multiple look-and-feels
– Abstract Factories for different screen components

• Generic instantiation – Objects are instantiated without having to identify a specific class type in
client code (Abstract Factory, Factory)
• Simplicity – Make instantiation easier: callers do not have to write long complex code to
instantiate and set up an object (Builder, Prototype pattern)
• Creation constraints – Creational patterns can put bounds on who can create objects, how they are
created, and when they are created
Builder Design Pattern

Builder Pattern says that "construct a complex object from simple objects using step-by-step
approach"

It is mostly used when object can't be created in single step like in the de-serialization of a complex
object.

Advantage of Builder Design Pattern

The main advantages of Builder Pattern are as follows:


o It provides clear separation between the construction and representation of an object.
o It provides better control over construction process.
o It supports to change the internal representation of objects.

104
When to Use Builder Pattern

1. When the process involved in creating an object is extremely complex, with lots of mandatory
and optional parameters
2. When an increase in the number of constructor parameters leads to a large list of constructors
3. When client expects different representations for the object that‘s constructed

Factory Method
Intent

 Define an interface for creating an object, but let subclasses decide which class to instantiate.
Factory Method lets a class defer instantiation to subclasses.
 Defining a "virtual" constructor.
 The new operator considered harmful.

Problem

A framework needs to standardize the architectural model for a range of applications, but allow for
individual applications to define their own domain objects and provide for their instantiation.
Discussion

Factory Method is to creating objects as Template Method is to implementing an algorithm. A superclass


specifies all standard and generic behavior (using pure virtual "placeholders" for creation steps), and then
delegates the creation details to subclasses that are supplied by the client.

 Factory Method makes a design more customizable and only a little more complicated. Other
design patterns require new classes, whereas Factory Method only requires a new operation.
 People often use Factory Method as the standard way to create objects; but it isn't necessary if:
the class that's instantiated never changes, or instantiation takes place in an operation that
subclasses can easily override (such as an initialization operation).
 Factory Method is similar to Abstract Factory but without the emphasis on families.

 Factory Methods are routinely specified by an architectural framework, and then implemented by
the user of the framework.

Structure

The implementation of Factory Method discussed in the Gang of Four (below) largely overlaps with that
of Abstract Factory. For that reason, the presentation in this chapter focuses on the approach that has
become popular since.

105
An increasingly popular definition of factory method is: a static method of a class that returns an object of
that class' type. But unlike a constructor, the actual object it returns might be an instance of a subclass.
Unlike a constructor, an existing object might be reused, instead of a new object created. Unlike a
constructor, factory methods can have different and more descriptive
names (e.g.Color.make_RGB_color(float red, float green, float blue) andColor.make_HSB_color(float
hue, float saturation, float brightness)

106
The client is totally decoupled from the implementation details of derived classes. Polymorphic
creation is now possible.

Example
The Factory Method defines an interface for creating objects, but lets subclasses decide which classes
to instantiate. Injection molding presses demonstrate this pattern. Manufacturers of plastic toys process
plastic molding powder, and inject the plastic into molds of the desired shapes. The class of toy (car,
action figure, etc.) is determined by the mold.

107
Usage of Factory Design Pattern

o When a class doesn't know what sub-classes will be required to create


o When a class wants that its sub-classes specify the objects to be created.
o When the parent classes choose the creation of objects to its sub-classes.

Structural Design pattern

Structural design patterns are concerned with how classes and objects can be composed, to form
larger structures.

The structural design patterns simplifies the structure by identifying the relationships.

These patterns focus on, how the classes inherit from each other and how they are composed from
other classes.

Types of structural design patterns

There are following 7 types of structural design patterns.

1. Adapter Pattern
Adapting an interface into another according to client expectation.
2. Bridge Pattern
Separating abstraction (interface) from implementation.
3. Composite Pattern
Allowing clients to operate on hierarchy of objects.
4. Decorator Pattern
Adding functionality to an object dynamically.
5. Facade Pattern
Providing an interface to a set of interfaces.
6. Flyweight Pattern
Reusing an object by sharing it.
7. proxy Pattern
Representing another object.

108
Bridge Design Pattern
The bridge pattern is a design pattern used in software engineering which is meant to "decouple an
abstraction from its implementation so that the two can vary independently". The bridge uses
encapsulation, aggregation, and can use inheritance to separate responsibilities into different classes.
When a class varies often, the features of object-oriented programming become very useful because
changes to a program's code can be made easily with minimal prior knowledge about the program. The
bridge pattern is useful when both the class and what it does vary often. The class itself can be thought
of as the implementation and what the class can do as the abstraction. The bridge pattern can also be
thought of as two layers of abstraction.
When there is only one fixed implementation, this pattern is known as the Pimpl idiom in the C++
world.
The bridge pattern is often confused with the adapter pattern. In fact, the bridge pattern is often
implemented using the class adapter pattern, e.g. in the Java code below.
Variant: The implementation can be decoupled even more by deferring the presence of the
implementation to the point where the abstraction is utilized.

 Abstraction (abstract class) defines the abstract interface maintains the Implementor
reference.
 RefinedAbstraction (normal class) extends the interface defined by Abstraction
 Implementor (interface)defines the interface for implementation classes
 ConcreteImplementor (normal class)implements the Implementor interface

Advantage of Bridge Pattern

o It enables the separation of implementation from the interface.


o It improves the extensibility.
o It allows the hiding of implementation details from the client.

109
Usage of Bridge Pattern
o When you don't want a permanent binding between the functional abstraction and its
implementation.
o When both the functional abstraction and its implementation need to extended using sub-
classes.
o It is mostly used in those places where changes are made in the implementation does not affect
the clients.

ADAPTER DESIGN PATTERN:

Intent

An Adapter Pattern says that just "converts the interface of a class into another interface that a
client wants". In other words, to provide the interface according to client requirement while using the
services of a class with a different interface.Wrap an existing class with a new interface. The Adapter
Pattern is also known as Wrapper. Impedance match an old component to a new system.

Adapter is about creating an intermediary abstraction that translates, or maps, the old component to the
new system. Clients call methods on the Adapter object which redirects them into calls to the legacy
component. This strategy can be implemented either with inheritance or with aggregation. Adapter
functions as a wrapper or modifier of an existing class. It provides a different or translated view of that
class.

Advantage of Adapter Pattern

o It allows two or more previously incompatible objects to interact.


o It allows reusability of existing functionality.

Usage of Adapter pattern:

It is used:

o When an object needs to utilize an existing class with an incompatible interface.


o When you want to create a reusable class that cooperates with classes which don't have
compatible interfaces.
o When you want to create a reusable class that cooperates with classes which don't have
compatible interfaces.

UML for Adapter Pattern:

There are the following specifications for the adapter pattern:

o Target Interface: This is the desired interface class which will be used by the clients.
o Adapter class: This class is a wrapper class which implements the desired target interface and
modifies the specific request available from the Adaptee class.
o Adaptee class: This is the class which is used by the Adapter class to reuse the existing
functionality and modify them for desired use.
o Client: This class will interact with the Adapter class.

110
BEHAVIORAL DESIGN PATTERN

A generic value of the software community for years has been, "maximize cohesion and minimize
coupling". The object-oriented design approach shown in Figure 21-1 is all about minimizing
coupling. Since the client is coupled only to an abstraction (i.e. a useful fiction), and not a particular
realization of that abstraction, the client could be said to be practicing "abstract coupling" . an object-
oriented variant of the more generic exhortation "minimize coupling".

A more popular characterization of this "abstract coupling" principle is ...

Program to an interface, not an implementation.


Clients should prefer the "additional level of indirection" that an interface (or an abstract base class)
affords. The interface captures the abstraction (i.e. the "useful fiction") the client wants to exercise,
and the implementations of that interface are effectively hidden.

Example:

"A Strategy defines a set of algorithms that can be used interchangeably. Modes of transportation to an
airport is an example of a Strategy. Several options exist such as driving one's own car, taking a taxi, an
airport shuttle, a city bus, or a limousine service. For some airports, subways and helicopters are also
available as a mode of transportation to the airport. Any of these modes of transportation will get a
traveler to the airport, and they can be used interchangeably. The traveler must chose the Strategy based
on tradeoffs between cost, convenience, and time."

111
STRATEGY DESIGN PATTERN:

The strategy pattern is a design pattern that allows a set of similar algorithms to be
defined and encapsulated in their own classes. The algorithm to be used for a
particular purpose may then be selected at run-time according to your requirements.

This design pattern can be used in common situations where classes differ only in
behavior. In this caseit is a good idea to separate these behavior algorithms in separate
classes which can be selected at run- time. This pattern defines a family of algorithms,
encapsulates each one, and makes them interchangeable. This separation allows
behaviors may vary independently of clients that use it. It also increases the flexibility
of the application allowing to add new algorithms in future.

The UML diagram below describes an implementation of the strategy design pattern.
This diagram consists of three parts:

 Client: this class uses interchangeable algorithms. It maintains a reference tothe


 StrategyBase: declares an interface common to all supported algorithms.
The client uses thisinterface to call the algorithm defined by a
ConcreteStrategy.
 ConcreteStrategy: this is the concrete strategy class inherited from the
StrategyBase class. Eachinstance provides a different algorithm that may be
used by the client.

112

You might also like