00000004-Ooad Unit-5
00000004-Ooad Unit-5
Events and signals, state machines, processes and threads, time and space.
State chart diagrams, component diagrams, deployment diagrams.
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.
State Machines
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
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
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
• 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.
• 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
• 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.
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
• 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
Statechart Diagrams
• 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
• 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
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
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
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
• 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
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
• 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.
• 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.
• 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.
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.
• 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 .
• 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.
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
• 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.
• 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.
• 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:
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.
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.
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
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
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.
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
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.
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
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.
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:
In core java, there are mainly three types of design patterns, which are further divided into their sub-parts:
Factory Pattern
Factory Method Pattern
Abstract Factory Pattern
Singleton Pattern
Prototype Pattern
Builder Pattern.
Memento Pattern
Observer Pattern
State Pattern
103
Strategy Pattern
Template Pattern
Visitor Pattern
• 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)
• 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.
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 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
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.
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
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.
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.
It is used:
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".
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:
112