Oom Uml
Oom Uml
- GENERAL OBJECTIVES
The objective of the training
This specialty trains senior technicians who, with the help of their capability to study the
needs of the society, can analyse (MERISE, UML), design and implement computer
applications in various fields.
1
2. Expected skills
→General skills
- Self-employed, work together as a team;
- Analyse, synthesize a professional document (French, English);
- Oral and written business communication (French, English);
- Participate in /conduct an approach to the management of a project; - Know and exploit
professional and institutional networks in the computer sectors.
→Specific skills
- Design and develop computer applications;
- implement and ensure the maintenance of computer programs;
- Develop software or systems based on software by following professional standards
adequately;
- Put in place and customize distributed applications;
- Diagnose the main faults affecting the computer system and replace defective parts; plan,
monitor and control a computer project.
3. Career opportunities
- Head of IT project;
- Software Consultant;
- Developer of applications;
- System Administrator
SPECIFIC OBJECTIVES
At the end of this course, the student should be able to
understand the Basic techniques of modeling computer systems
understand Object-oriented Methodologies
Model a system using UML (Unified Modeling Language)
2
understandthe various UML diagrams (structural and behavioral diagrams)
Understand and Construct the Class Diagram (attributes, association,
aggregation, composition,generalization, parameterized classes)
Understand Use Case diagram. understand how Interaction diagrams
(sequence diagram, collaboration diagram) do function in UML
Construct State Diagram and Activity Diagram of a system Use
object-oriented design (inheritance, encapsulation,
polymorphism, abstract interfaces, parameterized types) to design a system
Understand the various Design patterns in object-oriented design modeling
developed on object oriented software engineering
SEQUENTIAL METHODS
Below are some sequential methods
1) MERISE (Méthode d'Etude de Réalisation Informatique pour des Systèmesd'Entreprise)
MERISE is an Information System Design and Development methodology widely used in France.
3
Merise proceeds to separate treatment of data and processes, where the data-oriented view is modelled in
three stages, from conceptual, logical through to physical. Similarly, the process-oriented view passes
through the three stages of conceptual, organizational and operational. These stages in the modelling
process are paralleled by the stages of the life cycle: strategic planning, preliminary study, detailed study,
development, implementation and maintenance. It is a method of analysis based on the entityrelationship
model. By using Merise, you can design tables with relations to make a relational database.
4
• How do you achieve this function?
• Why do you do this function?
• When you do this function, what other functions must you do?
The following diagram illustrates how a function is expanded in "How" and "Why" directions in
a FAST diagram.
Example:
5
OBJECT-ORIENTED METHODOLOGIES
Below are some common object-oriented methodologies
4) Object Modeling Technique (OMT) is real world based modeling approach for software
modeling and designing. It was developed basically as a method to develop objectoriented
systems and to support object-oriented programming. It describes the static structure of the
system.
Object Modeling Technique is easy to draw and use. It is used in many applications like
telecommunication, transportation, compilers etc. It is also used in many real world problems.
OMT is one of the most popular object oriented development techniques used now-a-days. OMT
was developed by James Rambaugh.
Purpose of Object Modeling Technique:
• To test physical entity before construction of them.
• To make communication easier with the customers.
• To present information in an alternative way i.e. visualization.
• To reduce the complexity of software.
• To solve the real world problems.
Object Modeling Technique’s Models:
There are three main types of models that has been proposed by OMT:
1. Object Model:
Object Model encompasses the principles of abstraction, encapsulation, modularity,
hierarchy, typing, concurrency and persistence. Object Model basically emphasizes on
the object and class. Main concepts related with Object Model are classes and their
association with attributes. Predefined relationships in object model are aggregation and
generalization (multiple inheritance).
2. Dynamic Model:
Dynamic Model involves states, events and state diagram (transition diagram) on the
model. Main concepts related with Dynamic Model are states, transition between states
and events to trigger the transitions. Predefined relationships in object model are
aggregation (concurrency) and generalization.
3. Functional Model:
6
Functional Model focuses on the how data is flowing, where data is stored and different
processes. Main concepts involved in Functional Model are data, data flow, data store,
process and actors. Functional Model in OMT describes the whole processes and actions
with the help of data flow diagram (DFD).
Phases of Object Modeling Technique:
OMT has the following phases:
1. Analysis:
This the first phase of the object modeling technique. This phase involves the preparation
of precise and correct modelling of the real world problems. Analysis phase starts with
setting a goal i.e. finding the problem statement. Problem statement is further divided
into above discussed three models i.e. object, dynamic and functional model.
2. System Design:
This is the second phase of the object modeling technique and it comes after the analysis
phase. It determines all system architecture, concurrent tasks and data storage. High level
architecture of the system is designed during this phase.
3. Object Design:
Object design is the third phase of the object modelling technique and after system design
is over, this phase comes. Object design phase is concerned with classification of objects
into different classes and about attributes and necessary operations needed. Different
issues related with generalization and aggregation are checked.
4. Implementation:
This is the last phase of the object modeling technique. It is all about converting prepared
design into the software. Design phase is translated into the Implementation phase.
7
1. Inception - The idea for the project is stated. The development team
determines if the project is worth pursuing and what resources will be needed.
2. Elaboration - The project's architecture and required resources are further evaluated.
Developers consider possible applications of the software and costs associated with the
development.
3. Construction- The project is developed and completed. The software is designed, written,
and tested.
4. Transition - The software is released to the public. Final adjustments or updates are made
based on feedback from end users.
The RUP development methodology provides a structured way for companies to envision create
software programs. Since it provides a specific plan for each step of the development process, it
helps prevent resources from being wasted and reduces unexpected development costs.
8
7) UP (Unified Process) method
Unified process (UP) is a method which is responsible for the life cycle of software and
for the development of the software Object-Oriented methods. It’s a generic, iterative and
incremental method, contrary to sequential methods like MERISE and SADT. Thus according to
UP, to transform the user’s needs into software, the realization must necessarily present the
following characteristics:
- UP uses UML
- UP is controlled by the use case
- UP is centered on architecture
- UP is iterative and incremental
9
Creation of an object as a member of a class is called instantiation. Thus, object is an instance of
a class.
The constituents of a class are −
• A set of attributes for the objects that are to be instantiated from the class. Generally,
different objects of a class have some difference in the values of the attributes. Attributes
are often referred as class data.
• A set of operations that portray the behavior of the objects of the class. Operations are
also referred as functions or methods.
Example
Let us consider a simple class, Circle, that represents the geometrical figure circle in a two–
dimensional space. The attributes of this class can be identified as follows −
• x–coord, to denote x–coordinate of the center
• y–coord, to denote y–coordinate of the center
• a, to denote the radius of the circle
Some of its operations can be defined as follows −
• findArea(), method to calculate area
• findCircumference(), method to calculate circumference
• scale(), method to increase or decrease the radius
During instantiation, values are assigned for at least some of the attributes. If we create an object
my_circle, we can assign values like x-coord : 2, y-coord : 3, and a : 4 to depict its state. Now, if
the operation scale() is performed on my_circle with a scaling factor of 2, the value of the
variable a will become 8. This operation brings a change in the state of my_circle, i.e., the object
has exhibited certain behavior.
Encapsulation and Data Hiding
Encapsulation
Encapsulation is the process of binding both attributes and methods together within a class.
Through encapsulation, the internal details of a class can be hidden from outside. It permits the
elements of the class to be accessed from outside only through the interface provided by the
class.
10
Data Hiding
Typically, a class is designed such that its data (attributes) can be accessed only by its class
methods and insulated from direct outside access. This process of insulating an object’s data is
called data hiding or information hiding.
Example
In the class Circle, data hiding can be incorporated by making attributes invisible from outside
the class and adding two more methods to the class for accessing class data, namely −
• setValues(), method to assign values to x-coord, y-coord, and a
• getValues(), method to retrieve values of x-coord, y-coord, and a
Here the private data of the object my_circle cannot be accessed directly by any method that is
not encapsulated within the class Circle. It should instead be accessed through the methods
setValues() and getValues(). Message Passing
Any application requires a number of objects interacting in a harmonious manner. Objects in a
system may communicate with each other using message passing. Suppose a system has two
objects: obj1 and obj2. The object obj1 sends a message to object obj2, if obj1 wants obj2 to
execute one of its methods.
The features of message passing are −
• Message passing between two objects is generally unidirectional.
• Message passing enables all interactions between objects.
• Message passing essentially involves invoking class methods.
• Objects in different processes can be involved in message passing.
Inheritance
Inheritance is the mechanism that permits new classes to be created out of existing classes by
extending and refining its capabilities. The existing classes are called the base classes/parent
classes/super-classes, and the new classes are called the derived classes/child classes/subclasses.
The subclass can inherit or derive the attributes and methods of the super-class(es) provided that
the super-class allows so. Besides, the subclass may add its own attributes and methods and may
modify any of the super-class methods. Inheritance defines an “is – a” relationship.
11
Example
From a class Mammal, a number of classes can be derived such as Human, Cat, Dog, Cow, etc.
Humans, cats, dogs, and cows all have the distinct characteristics of mammals. In addition, each
has its own particular characteristics. It can be said that a cow “is – a” mammal.
Types of Inheritance
• Single Inheritance − A subclass derives from a single super-class.
• Multiple Inheritance − A subclass derives from more than one super-classes.
• Multilevel Inheritance − A subclass derives from a super-class which in turn is derived
from another class and so on.
• Hierarchical Inheritance − A class has a number of subclasses each of which may have
subsequent subclasses, continuing for a number of levels, so as to form a tree structure.
• Hybrid Inheritance − A combination of multiple and multilevel inheritance so as to form
a lattice structure.
The following figure depicts the examples of different types of inheritance.
12
Polymorphism
Polymorphism is originally a Greek word that means the ability to take multiple forms. In
objectoriented paradigm, polymorphism implies using operations in different ways, depending
upon the instance they are operating upon. Polymorphism allows objects with different internal
structures to have a common external interface. Polymorphism is particularly effective while
implementing inheritance.
Example
Let us consider two classes, Circle and Square, each with a method findArea(). Though the name
and purpose of the methods in the classes are same, the internal implementation, i.e., the
procedure of calculating area is different for each class. When an object of class Circle invokes
its findArea() method, the operation finds the area of the circle without any conflict with the
findArea() method of the Square class.
13
Exercises
1) Give the differences between:
a) Class and object
b) Single and multiple inheritance
c) Generalization and specialization
2) List and explain any two types of model you know
3) Define the following
a) Polymorphism
b) Inheritance
c) Encapsulation
d) Data binding
1) Let us consider two classes, Circle and Square, each with a method findArea().
Though the name and purpose of the methods in the classes are same, the internal
implementation, i.e., the procedure of calculating area is different for each class.
When an object of class Circle invokes its findArea() method, the operation finds
the area of the circle without any conflict with the findArea() method of the
Square class.
Produce the class for the above expression
14
• Rules to connect the building blocks
• Common mechanisms of UML
1) Things
Things are the most important building blocks of UML. Things can be −
• Structural
• Behavioral
• Grouping
• Annotational
2) Structural Things
Structural things define the static part of the model. They represent the physical and conceptual
elements. Following are the brief descriptions of the structural things.
d) Class −
A Class is a blueprint for an object. Objects and classes go hand in hand. We can't talk
about one without talking about the other. And the entire point of Object-Oriented Design is not
about objects, it's about classes, because we use classes to create objects. So a class describes
what an object will be, but it isn't the object itself.
In fact, classes describe the type of objects, while objects are usable instances of classes.
Each Object was built from the same set of blueprints and therefore contains the same
components (properties and methods). The standard meaning is that an object is an instance of a
class and object - Objects have states and behaviors.
Example
A dog has states - color, name, breed as well as behaviors -wagging, barking, eating. An object is
an instance of a class.
15
UML Class Notation
A class represent a concept which encapsulates state (attributes) and behavior (operations).
Each attribute has a type. Each operation has a signature. The class name is the only mandatory
information.
Class Name:
• The name of the class appears in the first partition.
Class Attributes:
• Attributes are shown in the second partition.
• The attribute type is shown after the colon.
• Attributes map onto member variables (data members) in code.
Class Operations (Methods):
• Operations are shown in the third partition. They are services the class provides.
16
• The return type of a method is shown after the colon at the end of the method signature.
• The return type of method parameters are shown after the colon following the parameter
name. Operations map onto class methods in code
Class Visibility
The +, - and # symbols before an attribute and operation name in a class denote the visibility of
the attribute and operation.
17
Perspectives of Class Diagram
The choice of perspective depends on how far along you are in the development process. During
the formulation of a domain model, for example, you would seldom move past the conceptual
perspective. Analysis models will typically feature a mix of conceptual and specification
perspectives. Design model development will typically start with heavy emphasis on the
specification perspective, and evolve into the implementation perspective.
A diagram can be interpreted from various perspectives:
• Conceptual: represents the concepts in the domain
• Specification: focus is on the interfaces of Abstract Data Type (ADTs) in the software
• Implementation: describes how classes will implement their interfaces
The perspective affects the amount of detail to be supplied and the kinds of relationships worth
presenting. As we mentioned above, the class name is the only mandatory information.
e) Object Notation
The object is represented in the same way as the class. The only difference is the name which is
underlined as shown in the following figure.
18
f) Interface
Interface defines a set of operations, which specify the responsibility of a class.
Interface is represented by a circle as shown in the following figure. It has a name which is
generally written below the circle.
g) Collaboration –
Collaboration defines an interaction between elements. Collaboration is represented by a dotted
eclipse as shown in the following figure. It has a name written inside the eclipse.
h) Use case –
Use case represents a set of actions performed by a system for a specific goal. Use case is
represented as an eclipse with a name inside it. It may contain additional responsibilities.
19
i) Component –
Component describes the physical part of a system. A component in UML is shown in the
following figure with a name inside. Additional elements can be added wherever required.
j) Node –
A node can be defined as a physical element that exists at run time such as the server, network,
etc. A node in UML is represented by a square box as shown in the following figure with a name.
A node represents the physical component of the system.
Behavioral Things
A behavioral thing consists of the dynamic parts of UML models. Following are the behavioral
things −
Interaction − Interaction is defined as a behavior that consists of a group of messages exchanged
among elements to accomplish a specific task.
State machine − State machine is useful when the state of an object in its life cycle is important.
It defines the sequence of states an object goes through in response to events. Events are external
factors responsible for state change
Grouping Things
Grouping things can be defined as a mechanism to group elements of a UML model together.
There is only one grouping thing available −
20
Package − Package is the only one grouping thing available for gathering structural and
behavioral things.
Annotational Things
Annotational things can be defined as a mechanism to capture remarks, descriptions, and
comments of UML model elements. Note - It is the only one Annotational thing available. A
note is used to render comments, constraints, etc. of an UML element.
Relationship
Relationship is another most important building block of UML. It is the connection
between model elements. A UML relationship is a type of model element that adds semantics to
a model by defining the structure and behavior between model elements.
There are four kinds of relationships available.
i) Association
21
Associations are relationships between classes in a UML Class Diagram. They are represented by
a solid line between classes. Associations are typically named using a verb or verb phrase which
reflects the real world problem domain.
Simple Association
• A structural link between two peer classes.
• There is an association between Class1 and Class2
Example: The figure below shows an example of simple association. There is an association that
connects the <<control>> class Class1 and <<boundary>> class Class2. The relationship is
displayed as a solid line connecting the two classes.
Degree of an Association
Degree of an association denotes the number of classes
involved in a connection. Degree may be unary, binary, or ternary.
• A unary relationship connects objects of the same class.
• A binary relationship connects objects of two classes.
• A ternary relationship connects objects of three or more classes.
Cardinality
Cardinality is expressed in terms of:
• one to one
• one to many
• many to many
In the generalization process, the common characteristics of classes are combined to form a
class in a higher level of hierarchy,
i.e., subclasses are combined to form a generalized super-class.
22
Thus, the specific classifier inherits the features of the more general classifier.
• Represents an "is-a" relationship.
• An abstract class name is shown in italics.
• SubClass1 and SubClass2 are specializations of SuperClass.
An example of inheritance hierarchy include. SubClass1 and SubClass2 are derived from
Superclass. The relationship is displayed as a solid line with a hollow arrowhead that points from
the child element to the parent element.
For example, “car is a kind of land vehicle”, or “ship is a kind of water vehicle”.
Specialization
Specialization is the reverse process of generalization. Here, the distinguishing features of groups
of objects are used to form specialized classes from existing classes. It can be said that the
subclasses are the specialized versions of the super-class.
Generalizatio Specializatio
23
iii) Realization
Realization can be defined as a relationship in which two elements are connected. One
element describes some responsibility, which is not implemented and the other one implements
them. This relationship exists in case of interfaces.
For example, the Owner interface might specify methods for acquiring property and disposing
of property. The Person and Corporation classes need to implement these methods, possibly in
very different
ways.
iv) Dependency
Dependency is a relationship
between two things in
which change in one element
also affects the other. If the
object is not stored in any
field, then this is modeled as a
dependency relationship.
• A special type of
association.
• Exists between two
classes if changes to the
definition of
24
one may cause changes to the other (but not the other way around).
• Class1 depends on Class2
The figure below shows an example of dependency. The relationship is displayed as a dashed
line with an open arrow.
The figure below shows another example of dependency. The Person class might have a hasRead
method with a Book parameter that returns true if the person has read the book (perhaps by
checking some database).
v) Aggregation
A special type of association.
• It represents a "part of" relationship.
• Class2 is part of Class1.
• Many instances (denoted by the *) of Class2 can be associated with Class1.
• Objects of Class1 and Class2 have separate lifetimes.
The figure below shows an example of aggregation. The relationship is displayed as a solid line
with a unfilled diamond at the association end, which is connected to the class that represents the
aggregate.
vi) Composition
• A special type of aggregation where parts are destroyed when the whole is destroyed.
• Objects of Class2 live and die with Class1.
• Class2 cannot stand by itself.
25
The figure below shows an example of composition. The relationship is displayed as a solid line
with a filled diamond at the association end, which is connected to the class that represents the
whole or composite.
UML Diagrams
UML diagrams are the ultimate output of the entire discussion. All the elements,
relationships are used to make a complete UML diagram and the diagram represents a system.
UML includes the following nine diagrams,
_ Class diagram
• Object diagram
• Use case diagram
• Sequence diagram
• Collaboration diagram
• Activity diagram
• Statechart diagram
• Deployment diagram
26
• Component diagram
UML - Architecture
Any real-world system is used by different users. The users can be developers, testers,
business people, analysts, and many more. Hence, before designing a system, the architecture is
made with different perspectives in mind. The most important part is to visualize the system from
the perspective of different viewers. The better we understand the better we can build the system.
UML plays an important role in defining different perspectives of a system. These perspectives
are −
• Design
• Implementation
• Process
• Deployment
Design of a system consists of classes, interfaces, and collaboration. UML provides class
diagram, object diagram to support this.
Implementation defines the components assembled together to make a complete physical
system. UML component diagram is used to support the implementation perspective. Process
defines the flow of the system. Hence, the same elements as used in Design are also used to
support this perspective.
Deployment represents the physical nodes of the system that forms the hardware. UML
deployment diagram is used to support this perspective.
B) Structural Modeling
The structural diagrams represent the static aspect of the system. These static aspects
represent those parts of a diagram, which forms the main structure and are therefore stable.
These static parts are represented by classes, interfaces, objects, components, and nodes.
27
The four structural diagrams are −
• Class diagram
• Object diagram
• Component diagram
• Deployment diagram
i) Class Diagram
Class diagrams are the most common diagrams used in UML. Class diagram consists of classes,
interfaces, associations, collaboration and constraints. Class diagrams basically represent the
object-oriented view of a system, which is static in nature.
Class diagram describes the attributes and operations of a class and also the constraints
imposed on the system. The class diagrams are widely used in the modeling of object-oriented
systems because they are the only UML diagrams, which can be mapped directly with
objectoriented languages.
The purpose of the class diagram can be summarized as − •
Analysis and design of the static view of an
application.
• Describe responsibilities of a system.
• Base for component and deployment diagrams.
• Forward and reverse engineering.
How to Draw a Class Diagram?
Class diagrams are the most popular UML diagrams used for construction of software
applications. It is very important to learn the drawing procedure of class diagram.
Class diagrams have a lot of properties to consider while drawing but here the diagram will be
considered from a top level view.
Class diagram is basically a graphical representation of the static view of the system and
represents different aspects of the application. A collection of class diagrams represent the whole
system.
The following points should be remembered while drawing a class diagram −
• The name of the class diagram should be meaningful to describe the aspect of the system.
• Each element and their relationships should be identified in advance.
• Responsibility (attributes and methods) of each class should be clearly identified
28
• For each class, minimum number of properties should be specified, as unnecessary
properties will make the diagram complicated.
• Use notes whenever required to describe some aspect of the diagram. At the end of the
drawing it should be understandable to the developer/coder.
• Finally, before making the final version, the diagram should be drawn on plain paper and
reworked as many times as possible to make it correct.
The following diagram is an example of an Order System of an application. It describes a
particular aspect of the entire application.
• First of all, Order and Customer are identified as the two elements of the system. They
have a one-to-many relationship because a customer can have multiple orders.
• Order class is an abstract class and it has two concrete classes (inheritance relationship)
SpecialOrder and NormalOrder.
• The two inherited classes have all the properties as the Order class. In addition, they have
additional functions like dispatch () and receive ().
The following class diagram has been drawn considering all the points mentioned above.
29
ii) Object Diagram
Object diagrams can be described as an instance of class diagram. Thus, these diagrams are
more close to real-life scenarios where we implement a system.
Object diagrams are a set of objects and their relationship is just like class diagrams. They also
represent the static view of the system.
The usage of object diagrams is similar to class diagrams but they are used to build prototype of
a system from a practical perspective.
The purpose of the object diagram can be summarized as –
• Forward and reverse engineering.
• Making the prototype of a system
• Object relationships of a system
• Static view of an interaction.
• Understand object behavior and their relationship from practical perspective
30
• The link in object diagram is used to connect objects.
• Objects and links are the two elements used to construct an object diagram.
After this, the following things are to be decided before starting the construction of the diagram
• The object diagram should have a meaningful name to indicate its purpose.
• The most important elements are to be identified.
• The association among objects should be clarified.
• Values of different elements need to be captured to include in the object diagram.
• Add proper notes at points where more clarity is required.
Example: The diagram below represents the Order management system which we have
discussed in the chapter Class Diagram. The following diagram is an instance of the system at a
particular time of purchase. It has the following objects.
• Customer
• Order
• SpecialOrder
• NormalOrder
Now the customer object (C) is associated with three order objects (O1, O2, and O3). These
order objects are associated with special order and normal order objects (S1, S2, and N1). The
customer has the following three orders with different numbers (12, 32 and 40) for the particular
time considered.
The customer can increase the number of orders in future and in that scenario the object
diagram will reflect that. If order, special order, and normal order objects are observed then you
will find that they have some values.
For orders, the values are 12, 32, and 40 which implies that the objects have these values
for a particular moment (here the particular time when the purchase is made is considered as the
moment) when the instance is captured
The same is true for special order and normal order objects which have number of orders
as 20, 30, and 60. If a different time of purchase is considered, then these values will change
accordingly.
The following object diagram has been drawn considering all the points mentioned above
31
iii) Component Diagram
Component diagrams represent a set of components and their relationships. These
components consist of classes, interfaces, or collaborations. Component diagrams represent the
implementation view of a system.
During the design phase, software artifacts (classes, interfaces, etc.) of a system are
arranged in different groups depending upon their relationship. Now, these groups are known as
components.
Finally, it can be said component diagrams are used to visualize the implementation.
The purpose of the component diagram can be summarized as −
• Visualize the components of a system.
• Model the database schema.
• Construct executables by using forward and reverse engineering.
• Describe the organization and relationships of the components.
32
This diagram is very important as without it the application cannot be implemented efficiently. A
well-prepared component diagram is also important for other aspects such as application
performance, maintenance, etc.
Before drawing a component diagram, the following artifacts are to be identified clearly −
• Files used in the system.
• Libraries and other artifacts relevant to the application.
• Relationships among the artifacts.
After identifying the artifacts, the following points need to be kept in mind.
• Use a meaningful name to identify the component for which the diagram is to be drawn.
• Prepare a mental layout before producing the using tools.
• Use notes for clarifying important points.
Example: Following is a component diagram for order management system. Here, the artifacts
are files. The diagram shows the files in the application and their relationships. In actual, the
component diagram also contains dlls, libraries, folders, etc.
In the following diagram, four files are identified and their relationships are produced.
Component diagram cannot be matched directly with other UML diagrams discussed so far as it
is drawn for completely different purpose.
The following component diagram has been drawn considering all the points mentioned above.
33
iv) Deployment Diagram
The term Deployment itself describes the purpose of the diagram.
Deployment diagrams are used for describing the hardware components, where software
components are deployed. Component diagrams and deployment diagrams are closely related.
Deployment diagrams are a set of nodes and their relationships. These nodes are physical entities
where the components are deployed.
Deployment diagrams are used for visualizing the deployment view of a system. This is
generally used by the deployment team.
The purpose of deployment diagrams can be described as −
• Visualize the hardware topology of a system.
• Describe the hardware components used to deploy software components.
• Describe the runtime processing nodes.
34
• Caching server
• Server
The application is assumed to be a web-based application, which is deployed in a clustered
environment using server 1, server 2, and server 3. The user connects to the application using the
Internet. The control flows from the caching server to the clustered environment.
The following deployment diagram has been drawn considering all the points mentioned above.
C) Behavioral Modeling
Behavioral model describes the interaction in the system. It represents the interaction among the
structural diagrams. Behavioral modeling shows the dynamic nature of the system. They consist
of the following −
• Use case diagram
• Sequence diagram
• Collaboration diagram
• Statechart diagram
• Activity diagram
35
i) Use Case Diagram
Use case diagrams are a set of use cases, actors, and their relationships. They represent the use
case view of a system.
A use case represents a particular functionality of a system. Hence, use case diagram is
used to describe the relationships among the functionalities and their internal/external controllers.
These controllers are known as actors.
The purpose of use case diagram is to capture the dynamic aspect of a system.
However, this definition is too generic to describe the purpose, as other four diagrams (activity,
sequence, collaboration, and Statechart) also have the same purpose. We will look into some specific
purpose, which will distinguish it from other four diagrams.
Purposes of use case diagrams can be said to be as follows −
• Used to gather the requirements of a system.
• Used to get an outside view of a system.
• Identify the external and internal factors influencing the system.
• Show the interaction among the requirements are actors.
How to Draw a Use Case Diagram?
Use case diagrams are considered for high level requirement analysis of a system. When
the requirements of a system are analyzed, the functionalities are captured in use cases. We can
say that use cases are nothing but the system functionalities written in an organized manner.
The second thing which is relevant to use cases are the actors. Actors can be defined as
something that interacts with the system.
Actors can be a human user, some internal applications, or may be some external
applications. When we are planning to draw a use case diagram, we should have the following
items identified.
• Functionalities to be represented as use case
• Actors
• Relationships among the use cases and actors.
Use case diagrams are drawn to capture the functional requirements of a system. After
identifying the above items, we have to use the following guidelines to draw an efficient use case
diagram
36
• The name of a use case is very important. The name should be chosen in such a way so that it
can identify the functionalities performed.
• Give a suitable name for actors.
• Show relationships and dependencies clearly in the diagram.
• Do not try to include all types of relationships, as the main purpose of the diagram is to
identify the requirements.
• Use notes whenever required to clarify some important points.
Example:Following is a sample use case diagram representing the order management system.
Hence, if we look into the diagram then we will find three use cases (Order, SpecialOrder, and
NormalOrder) and one actor which is the customer.
The SpecialOrder and NormalOrder use cases are extended from Order use case. Hence,
they have extended relationship. Another important point is to identify the system boundary,
which is shown in the picture. The actor Customer lies outside the system as it is an external user
of the system.
37
UML - Interaction Diagrams
From the term Interaction, it is clear that the diagram is used to describe some type of
interactions among the different elements in the model. This interaction is a part of dynamic
behavior of the system.
This interactive behavior is represented in UML by two diagrams known as Sequence
diagram and Collaboration diagram. The basic purpose of both the diagrams are similar.
Sequence diagram emphasizes on time sequence of messages and collaboration diagram
emphasizes on the structural organization of the objects that send and receive messages.
Purpose of Interaction Diagrams
The purpose of interaction diagrams is to visualize the interactive behavior of the system.
Visualizing the interaction is a difficult task. Hence, the solution is to use different types of
models to capture the different aspects of the interaction.
Sequence and collaboration diagrams are used to capture the dynamic nature but from a different
angle.
The purpose of interaction diagram is −
• To capture the dynamic behaviour of a system.
• To describe the message flow in the system.
• To describe the structural organization of the objects.
• To describe the interaction among objects.
How to Draw an Interaction Diagram?
As we have already discussed, the purpose of interaction diagrams is to capture the dynamic
aspect of a system. So to capture the dynamic aspect, we need to understand what a dynamic
aspect is and how it is visualized. Dynamic aspect can be defined as the snapshot of the running
system at a particular moment
We have two types of interaction diagrams in UML. One is the sequence diagram and the
other is the collaboration diagram. The sequence diagram captures the time sequence of the
message flow from one object to another and the collaboration diagram describes the
organization of objects in a system taking part in the message flow.
Following things are to be identified clearly before drawing the interaction diagram
• Objects taking part in the interaction.
• Message flows among the objects.
38
• The sequence in which the messages are flowing.
• Object organization.
Following are two interaction diagrams modeling the order management system. The first
diagram is a sequence diagram and the second is a collaboration diagram
Example:
The sequence diagram has four objects (Customer, Order, SpecialOrder and NormalOrder). The
following diagram shows the message sequence for SpecialOrder object and the same can be
used in case of NormalOrder object. It is important to understand the time sequence of message
flows. The message flow is nothing but a method call of an object.
The first call is sendOrder () which is a method of Order object. The next call is confirm ()
which is a method of SpecialOrder object and the last call is Dispatch () which is a method of
SpecialOrder object. The following diagram mainly describes the method calls from one object
to another, and this is also the actual scenario when the system is running.
39
iii) The Collaboration Diagram
The second interaction diagram is the collaboration diagram. It shows the object organization as
seen in the following diagram. In the collaboration diagram, the method call sequence is
indicated by some numbering technique. The number indicates how the methods are called one
after another. We have taken the same order management system to describe the collaboration
diagram.
Method calls are similar to that of a sequence diagram. However, difference being the
sequence diagram does not describe the object organization, whereas the collaboration diagram
shows the object organization.
To choose between these two diagrams, emphasis is placed on the type of requirement. If
the time sequence is important, then the sequence diagram is used. If organization is required,
then collaboration diagram is used.
40
iv) Statechart Diagram
The name of the diagram itself clarifies the purpose of the diagram and other details. It describes
different states of a component in a system. The states are specific to a component/object of a
system.
41
A Statechart diagram describes a state machine. State machine can be defined as a machine
which defines different states of an object and these states are controlled by external or internal
events.
Activity diagram explained in the next chapter, is a special kind of a Statechart diagram.
As Statechart diagram defines the states, it is used to model the lifetime of an object.
• 42
•
Before drawing a Statechart diagram we should clarify the following points − Identify
the important objects to be analyzed.
Identify the states.
Identify the events.
Example:Following is an example of a Statechart diagram where the state of Order object is
analyzed
The first state is an idle state from where the process starts. The next states are arrived for events
like send request, confirm request, and dispatch order. These events are responsible for the state
changes of order object.
During the life cycle of an object (here order object) it goes through the following states
and there may be some abnormal exits. This abnormal exit may occur due to some problem in
the system. When the entire life cycle is complete, it is considered as a complete transaction as
shown in the following figure. The initial and final state of an object is also shown in the
following figure.
v) Activity Diagram
Activity diagram is another important diagram in UML to describe the dynamic aspects of
the system.
43
Activity diagram is basically a flowchart to represent the flow from one activity to another
activity. The activity can be described as an operation of the system.
The control flow is drawn from one operation to another. This flow can be sequential, branched,
or concurrent. Activity diagrams deal with all type of flow control by using different elements
such as fork, join, etc
• 44
•
function performed by the system. After identifying the activities, we need to understand how
they are associated with constraints and conditions.
Before drawing an activity diagram, we should identify the following elements −
Activities
Association
Conditions
• Constraints
Once the above-mentioned parameters are identified, we need to make a mental layout of the
entire flow. This mental layout is then transformed into an activity diagram.
Example: Following is an example of an activity diagram for order management system. In the
diagram, four activities are identified which are associated with conditions. One important point
should be clearly understood that an activity diagram cannot be exactly matched with the code.
The activity diagram is made to understand the flow of activities and is mainly used by the
business users
Following diagram is drawn with the four main activities −
• Send order by the customer
• Receipt of the order
• Confirm the order
• Dispatch the order
After receiving the order request, condition checks are performed to check if it is normal or
special order. After the type of order is identified, dispatch activity is performed and that is
marke d as the termination of the process.
45
CHAPTER THREE: Object Oriented Analysis & Design
Object-Oriented Analysis
Object–Oriented Analysis (OOA) is the procedure of identifying software engineering
requirements and developing software specifications in terms of a software system’s object
model, which comprises of interacting objects.
The main difference between object-oriented analysis and other forms of analysis is that
in object-oriented approach, requirements are organized around objects, which integrate both
data and functions. They are modelled after real-world objects that the system interacts with. In
traditional analysis methodologies, the two aspects - functions and data - are considered
separately.
Grady Booch has defined OOA as, “Object-oriented analysis is a method of analysis that
examines requirements from the perspective of the classes and objects found in the vocabulary
of the problem domain”.
The primary tasks in object-oriented analysis (OOA) are −
• Identifying objects
• Organizing the objects by creating object model diagram
• Defining the internals of the objects, or object attributes
•
• 46
•
47
system is called a subsystem. Object-oriented decomposition identifies individual autonomous
objects in a system and the communication among these objects.
The advantages of decomposition are −
• The individual components are of lesser complexity, and so more understandable and
manageable.
• It enables division of workforce having specialized skills.
• It allows subsystems to be replaced or modified without affecting other subsystems.
Identifying Concurrency
Concurrency allows more than one objects to receive events at the same time and more than one
activity to be executed simultaneously. Concurrency is identified and represented in the dynamic
model.
To enable concurrency, each concurrent element is assigned a separate thread of control. If the
concurrency is at object level, then two concurrent objects are assigned two different threads of
• 48
control. If two operations of a single object are concurrent in nature, then that object is split
among different threads.
Concurrency is associated with the problems of data integrity, deadlock, and starvation. So a
clear strategy needs to be made whenever concurrency is required. Besides, concurrency requires
to be identified at the design stage itself, and cannot be left for implementation stage.
Identifying Patterns
While designing applications, some commonly accepted solutions are adopted for some
categories of problems. These are the patterns of design. A pattern can be defined as a
documented set of building blocks that can be used in certain types of application development
problems.
Some commonly used design patterns are −
• Façade pattern
• Model view separation pattern
• Observer pattern
• Model view controller pattern
• Publish subscribe pattern
• Proxy pattern
Controlling Events
During system design, the events that may occur in the objects of the system need to be
identified and appropriately dealt with.
An event is a specification of a significant occurrence that has a location in time and space.
There are four types of events that can be modelled, namely −
• Signal Event − A named object thrown by one object and caught by another object.
• Call Event − A synchronous event representing dispatch of an operation.
• Time Event − An event representing passage of time.
• Change Event − An event representing change in state.
49
Handling Boundary Conditions
The system design phase needs to address the initialization and the termination of the system as
a whole as well as each subsystem. The different aspects that are documented are as follows −
The start–up of the system, i.e., the transition of the system from non-initialized state to steady
state.
The termination of the system, i.e., the closing of all running threads, cleaning up of
resources, and the messages to be sent.
• The initial configuration of the system and the reconfiguration of the system when
needed.
• Foreseeing failures or undesired termination of the system.
Boundary conditions are modelled using boundary use cases.
Object Design
After the hierarchy of subsystems has been developed, the objects in the system are identified
and their details are designed. Here, the designer details out the strategy chosen during the
system design. The emphasis shifts from application domain concepts toward computer
concepts. The objects identified during analysis are etched out for implementation with an aim to
minimize execution time, memory consumption, and overall cost.
Object design includes the following phases −
• Object identification
• Object representation, i.e., construction of design models
• Classification of operations
• Algorithm design
• Design of relationships
• Implementation of control for external interactions
• Package classes and associations into modules
Object Identification
The first step of object design is object identification. The objects identified in the object–
oriented analysis phases are grouped into classes and refined so that they are suitable for actual
implementation.
The functions of this stage are −
50
•
Object Representation
Once the classes are identified, they need to be represented using object modelling
techniques.
This stage essentially involves constructing UML diagrams.
There are two types of design models that need to be produced −
• Static Models − To describe the static structure of a system using class diagrams and
object diagrams.
• Dynamic Models − To describe the dynamic structure of a system and show the
interaction between classes using interaction diagrams and state–chart diagrams.
Classification of Operations
In this step, the operation to be performed on objects are defined by combining the three models
developed in the OOA phase, namely, object model, dynamic model, and functional model. An
operation specifies what is to be done and not how it should be done.
The following tasks are performed regarding operations −
• The state transition diagram of each object in the system is developed.
• Operations are defined for the events received by the objects.
• Cases in which one event triggers other events in same or different objects are identified.
• The sub–operations within the actions are identified.
• The main actions are expanded to data flow diagrams.
Algorithm Design
The operations in the objects are defined using algorithms. An algorithm is a stepwise procedure
that solves the problem laid down in an operation. Algorithms focus on how it is to be done.
There may be more than one algorithm corresponding to a given operation. Once the alternative
algorithms are identified, the optimal algorithm is selected for the given problem domain. The
metrics for choosing the optimal algorithm are −
51
• Computational Complexity − Complexity determines the efficiency of an algorithm in
terms of computation time and memory requirements.
• Flexibility − Flexibility determines whether the chosen algorithm can be implemented
suitably, without loss of appropriateness in various environments.
• Understandability − This determines whether the chosen algorithm is easy to
understand and implement.
52
Design of Relationships
The strategy to implement the relationships needs to be chalked out during the object design
phase. The main relationships that are addressed comprise of associations, aggregations, and
inheritances.
The designer should do the following regarding associations −
• Identify whether an association is unidirectional or bidirectional.
• Analyze the path of associations and update them if necessary.
• Implement the associations as a distinct object, in case of many–to-many relationships;
or as a link to other object in case of one–to-one or one–to-many relationships.
Regarding inheritances, the designer should do the following −
• Adjust the classes and their associations.
• Identify abstract classes.
• Make provisions so that behaviors are shared when needed.
Implementation of Control
The object designer may incorporate refinements in the strategy of the state–chart model. In
system design, a basic strategy for realizing the dynamic model is made. During object
design, this strategy is aptly embellished for appropriate implementation.
The approaches for implementation of the dynamic model are −
• Represent State as a Location within a Program − This is the traditional
proceduredriven approach whereby the location of control defines the program state. A
finite state machine can be implemented as a program. A transition forms an input
statement, the main control path forms the sequence of instructions, the branches form
the conditions, and the backward paths form the loops or iterations.
• State Machine Engine − This approach directly represents a state machine through a
state machine engine class. This class executes the state machine through a set of
transitions and actions provided by the application.
• Control as Concurrent Tasks − In this approach, an object is implemented as a task in
the programming language or the operating system. Here, an event is implemented as an
inter-task call. It preserves inherent concurrency of real objects.
53
Packaging Classes
In any large project, meticulous partitioning of an implementation into modules or packages
is important. During object design, classes and objects are grouped into packages to enable
multiple groups to work cooperatively on a project.
The different aspects of packaging are −
• Hiding Internal Information from Outside View − It allows a class to be viewed as a
“black box” and permits class implementation to be changed without requiring any
clients of the class to modify code.
• Coherence of Elements − An element, such as a class, an operation, or a module, is
coherent if it is organized on a consistent plan and all its parts are intrinsically related
so that they serve a common goal.
• Construction of Physical Modules − The following guidelines help while constructing
physical modules − o Classes in a module should represent similar things or
components in the same composite object.
o Closely connected classes should be in the same module.
o Unconnected or weakly connected classes should be placed in separate modules.
o Modules should have good cohesion, i.e., high cooperation among its
components. o A module should have low coupling with other modules,
i.e., interaction or interdependence between modules should be minimum.
Design Optimization
The analysis model captures the logical information about the system, while the design model
adds details to support efficient information access. Before a design is implemented, it should be
optimized so as to make the implementation more efficient. The aim of optimization is to
minimize the cost in terms of time, space, and other metrics.
However, design optimization should not be excess, as ease of implementation, maintainability,
and extensibility are also important concerns. It is often seen that a perfectly optimized design is
more efficient but less readable and reusable. So the designer must strike a balance between the
two.
The various things that may be done for design optimization are −
• Add redundant associations
54
• Omit non-usable associations
• Optimization of algorithms
• Save derived attributes to avoid re-computation of complex expressions
Addition of Redundant Associations
During design optimization, it is checked if deriving new associations can reduce access
costs. Though these redundant associations may not add any information, they may increase
the efficiency of the overall model.
Omission of Non-Usable Associations
Presence of too many associations may render a system indecipherable and hence reduce the
overall efficiency of the system. So, during optimization, all non-usable associations are
removed.
Optimization of Algorithms
In object-oriented systems, optimization of data structure and algorithms are done in a
collaborative manner. Once the class design is in place, the operations and the algorithms need to
be optimized.
Optimization of algorithms is obtained by −
• Rearrangement of the order of computational tasks
• Reversal of execution order of loops from that laid down in the functional model
• Removal of dead paths within the algorithm Saving and Storing of Derived Attributes
Derived attributes are those attributes whose values are computed as a function of other attributes
(base attributes). Re-computation of the values of derived attributes every time they are needed is
a time–consuming procedure. To avoid this, the values can be computed and stored in their
computed forms.
However, this may pose update anomalies, i.e., a change in the values of base attributes with no
corresponding change in the values of the derived attributes. To avoid this, the following steps
are taken −
• With each update of the base attribute value, the derived attribute is also re-computed.
• All the derived attributes are re-computed and updated periodically in a group rather
than after each update.
55
Design Documentation
Documentation is an essential part of any software development process that records the
procedure of making the software. The design decisions need to be documented for any non–
trivial software system for transmitting the design to others.
Usage Areas
Though a secondary product, a good documentation is indispensable, particularly in the
following areas −
• In designing software that is being developed by a number of developers
• In iterative software development strategies
• In developing subsequent versions of a software project
• For evaluating a software
• For finding conditions and areas of testing
• For maintenance of the software.
Contents
A beneficial documentation should essentially include the following contents − •
High–level system architecture − Process diagrams and module diagrams
• Key abstractions and mechanisms − Class diagrams and object diagrams.
• Scenarios that illustrate the behavior of the main aspects − Behavioral diagrams
Features
The features of a good documentation are −
• Concise and at the same time, unambiguous, consistent, and complete
• Traceable to the system’s requirement specifications
• Well-structured
• Diagrammatic instead of descriptive
Exercses:
56
3) Choose a system of your choice and do the following
- Draw the class diagram
- Draw the sequence diagram
- Draw the usecase diagram
57
Implementation
SingleObject class provides a static method to
get its static instance to outside world.
SingletonPatternDemo, our demo class will
use SingleObject class to get a SingleObject
object.
b) Factory
Creates objects without exposing the instantiation logic to the client and Refers to the newly created
object through a common interface.
Implementation
FactoryPatternDemo, our demo class will
use ShapeFactory to get a Shape object. It
will pass information (CIRCLE /
RECTANGLE / SQUARE) to ShapeFactory
to get the type of object it needs.
c) Builder
Builder pattern builds a complex
object using simple objects and using a
step by step approach.
Implementation
58
We are going to create an Item interface
representing food items such as burgers and cold
drinks and concrete classes implementing the
Item interface and a Packing interface
representing packaging of food items and
concrete classes implementing the Packing
interface as burger would be packed in wrapper
and cold drink would be packed as bottle.
We then create a Mealclass having
ArrayList of Item and a MealBuilderto build
different types of Meal objects by combining
Item. BuilderPatternDemo, our demo class will
use MealBuilder to build a Meal.
d) Prototype Pattern
Prototype pattern refers to creating duplicate object while keeping performance in mind. This
type of design pattern comes under creational pattern as this pattern provides one of the best
ways to create an object.
This pattern involves implementing a prototype interface which tells to create a clone of the
current object. This pattern is used when creation of object directly is costly. For example, an
object is to be created after a costly database operation. We can cache the object, returns its clone
on next request and update the database as and when needed thus reducing database calls.
Implementation
59
e) Abstract Pattern
Provide an interface for creating families of related or dependent objects without specifying their
concrete classes
2. Structural Patterns
Structural design patterns define the relationships between objects. Structural patterns provide
different ways to create a class structure, for example using inheritance and composition to
create a large object from small objects. Types Of Structure Patterns
a) Adapter Pattern
This pattern involves a single class which is responsible to join functionalities of independent
or incompatible interfaces. A real life example could be a case of card reader which acts as an
adapter between memory card and a laptop. Youplugin the memory card into card reader and
card reader into the laptop so that memory card can be read via laptop.
Implementation
We have a MediaPlayer interface and a concrete
class AudioPlayerimplementing the
MediaPlayerinterface. AudioPlayer can play
mp3 format audio files by default.
We are having another interface
AdvancedMediaPlayer and concrete classes
implementing the AdvancedMediaPlayer
interface. These classes can play vlc and mp4
format files.
We want to make AudioPlayer to play other
formats as well. To attain this, we have created
60
an adapter class MediaAdapter which implements the MediaPlayer interface and uses AdvancedMediaPlayer
objects to play the required format.
AudioPlayer uses the adapter class MediaAdapter passing it the desired audio type without knowing the
actual class which can play the desired format. AdapterPatternDemo, our demo class will use AudioPlayerclass to
play various formats.
b) Bridge Pattern
Bridge is used when we need to decouple an abstraction from its implementation so that the
two can vary independently.This pattern involves an interface which acts as a bridge which
makes the functionality of concrete classes independent from interface implementer classes. Both
types of classes can be altered structurally without affecting each other.
Implementation
We have a DrawAPIinterface which is acting as a bridge implementer and concrete classes
RedCircle,
GreenCircleimplementing the
DrawAPIinterface. Shape is an
abstract class and will use object of
DrawAPI. BridgePatternDemo, our
demo class will use Shape class to
draw different colored circle.
c) Composite Pattern
Composite pattern is used where
we need to treat a group of objects in similar way as a single object. Composite pattern composes
objects in term of a tree structure to represent part as well as whole hierarchy. This type of design
pattern comes under structural pattern as this pattern creates a tree structure of group of objects.
Compose objects into tree structures to represent part-whole hierarchies. Composite lets
clients treat individual objects and composition of objects uniformly.
61
Implementation
We have a classes Button,
Label,Textfieldand panel acting as
composite pattern subclasses to the super
class Panel.The subclass Button,
Label,Textfieldat the second level acts as a
composite pattern to the subclassPanelof
the first level
d) Decorator Pattern
Decorator pattern allows a user to add new functionality to an existing object without altering
its structure. This pattern creates a decorator class which wraps the original class and provides
additional functionality keeping class methods signature intact.
Implementation
We're going to create a Shape interface and
concrete classes implementing the Shape
interface. We will then create an abstract
decorator class Shape Decorator implementing
the Shape interface and having Shape object as
its instance variable.
Red Shape Decorator is concrete class
implementing Shape Decorator.
Decorator Pattern Demo, our demo class will
use Red Shape Decorator to decorate Shape
objects.
e) Facade Pattern
Facade pattern hides the complexities of the system and provides an interface to the client
using which the client can access the system. Provide a unified interface to access the interfaces
in a subsystem. Façade defines a higher-level
Interface that makes the subsystem easier to use
62
Implementation
We are going to create a Shape
interface and concrete classes
implementing the Shape interface. A
facade class Shape Maker is defined
as a next step.
Shape Maker class uses the concrete
classes to delegate user calls to these
classes. Façade Pattern Demo, our
demo class, will use Shape Maker
class to show the results.
f) Flyweight Pattern
Flyweight pattern is primarily used to reduce the number of objects created and to decrease
memory footprint and increase performance. Flyweight pattern tries to reuse already existing
similar kind objects by storing them and creates new object when no matching object is found
Implementation
We are going to create a Shape interface and
concrete class Circle implementing the Shape
interface. A factory class Shape Factory is
defined as a next step.
Shape Factory has a Hash Map of
Circle having key as color of the Circle object.
Whenever a request comes to create a circle of
particular color to Shape Factory, it checks the
circle object in its Hash Map, if object of Circle
found, that object is returned otherwise a new
object is created, stored in hash map for future
use, and returned to client.
63
Fly Weight Pattern Demo, our demo class, will use Shape Factory to get a Shape object.
It will pass information (red / green / blue/ black / white) to Shape Factory to get the circle of
desired color it needs.
g) Proxy Pattern
In proxy pattern, a class represents functionality of another class. This type of design pattern
comes under structural pattern.
In proxy pattern, we create object having original object to interface its functionality to outer
world.
Implementation
We are going to create an Image
interface and concrete classes
implementing the Image interface.
Proxy Image is a proxy class to
reduce memory footprint of Real
Image object loading.
Proxy Pattern Demo, our demo
class, will use Proxy Image to get an
Image object to load and display as it
needs.
3. Behavioral Patterns
Behavioral design
patterns describe the behavior of
objects, such as the way they
communicate with each other.
Behavioral patterns provide
64
solution for the better interaction between objects and how to provide lose coupling and
flexibility to extend easily.
Implementation
We have created an abstract class Abstract Logger with a level of logging. Then we have
created three types of loggers extending the Abstract Logger. Each logger checks the level of
message to its level and print accordingly otherwise does not print and pass the message to its
next logger.
b) Command Pattern
Command pattern is a data driven design pattern and falls under behavioral pattern category.
A request is wrapped under an object as command and passed to invoker object. Invoker object
looks for the appropriate object which can handle this command and passes the command to the
corresponding object which executes the command.
Implementation
We have created an interface Order which is acting as a command. We have created a
65
Stock class which acts as a request. We have concrete command classes Buy Stock and Sell
Stock implementing Order interface
which will do actual command
processing. A class Broker is created
which acts as an invoker object. It can
take and place orders.
Broker object uses command
pattern to identify which object will
execute which command based on the
type of command. Command Pattern
Demo, our demo class, will use Broker
class to demonstrate command pattern.
c) Interpreter Pattern
Is used to define a grammatical representation for a language and provides an interpreter to
deal with this grammar.
The best example of this pattern is java compiler that interprets the java source code into byte
code that is understandable by JVM (java visual machine). Google Translator is also an example
of an interpreter pattern where the input can be in any language and we can get the output
interpreted in another language.
d) Iterator Pattern
Iterator pattern in one of the behavioral pattern and it’s used to provide a standard way to traverse through
a group of Objects. Iterator pattern is widely used in Java Collection Framework where Iterator interface
66
e) Mediator Pattern
Mediator pattern is used to reduce communication complexity between multiple objects or classes. The
mediator design pattern is used to provide a centralized communication medium between different
objects in a system. The mediator design pattern is very helpful in an enterprise application where
multiple objects are interacting with each other.
f) Memento Pattern
The memento design pattern is used when we want to save the state of an object so that
we can restore later on. Memento pattern is used to implement this in such a way that the saved
state data of the object is not accessible outside of the object, this protects the integrity of saved
state data.
Memento pattern is implemented with two objects – Originator and Caretaker. The originator is
the object whose state needs to be saved and restored and it uses an inner class to save the state
of Object. The inner class is called Memento and it’s private so that it can’t be accessed from
other objects.
Implementation
Memento pattern uses three actor
classes. Memento contains state of an
object to be restored. Originator creates
and stores states in Memento objects
and Caretaker object is responsible to
restore object state from Memento. We
have created classes Memento,
Originator and Care Taker. Memento
Pattern Demo, our demo class, will use
Care Taker and Originator objects to
show restoration of object states.
67
g) Observer Pattern
Observer design pattern is useful when you are interested in the state of an object and want to
get notified whenever there is any change. In observer pattern, the object that watch on the state
of another object are called Observer and the object that is being watched is called Subject.
Implementation
Observer pattern uses three actor
classes. Subject, Observer and Client.
Subject is an object having methods to
attach and detach observers to a client
object. We have created an abstract class
Observer and a concrete class Subject that
is extending class Observer.
Observer Pattern Demo, our demo class,
will use Subject and concrete class object
to show observer pattern in action.
h) State Pattern
In State pattern, we create objects which represent various states and a context object whose
behavior varies as its state object changes.
68
Implementation
We are going to create a State interface
defining an action and concrete state
classes implementing the State interface.
Context is a class which carries a State.
State Pattern Demo, our demo class, will
use Context and state objects to
demonstrate change in Context behavior
based on type of state it is in.
i) Strategy Pattern
Strategy pattern is used when we have multiple algorithm for a specific task and client
decides the actual implementation to be used at runtime. In Strategy pattern, we create objects
which represent various strategies and a context object whose behavior varies as per its strategy
object. The strategy object changes the executing algorithm of the context object.
Implementation
We are going to create a Strategy interface defining an action and concrete strategy classes
implementing the Strategy interface.
Context is a class which uses a Strategy.
Strategy Pattern Demo, our demo class,
will use Context and strategy objects to
demonstrate change in Context behavior
based on strategy it deploys or uses.
69
Suppose we want to provide an algorithm to build a house. The steps need to be performed to
build a house are – building a foundation, building pillars, building walls, and windows. The
important point is that we can’t change the order of execution because we can’t build windows
before building the foundation. So, in this case, we can create a template method that will use
different methods to build the house
Implementation
We are going to create a Game abstract class
defining operations with a template method
set to be final so that it cannot be overridden.
Cricket and Football are concrete classes that
extend Game and override its methods.
Template Pattern Demo, our demo class, will
use Game to demonstrate use of template
pattern.
Visitor Pattern
Visitor pattern is used when we have to perform an operation on a group of similar kind
of Objects. With the help of visitor pattern, we can move the operational logic from the objects to
another class.
For example, think of a Shopping cart where we can add a different type of items
(Elements), when we click on the checkout button, it calculates the total amount to be paid. Now
we can have the calculation logic in item classes or we can move out this logic to another class
using visitor pattern.
70
Implementation
We are going to create a Computer Part interface
defining accept operation. Keyboard, Mouse, Monitor
and Computer are concrete classes implementing
Computer Part interface. We will define another
interface Computer Part Visitor which will define a
visitor class operations. Computer uses concrete visitor
to do corresponding action.
Visitor Pattern Demo, our demo class, will use
Computer and Computer Part Visitor classes to
demonstrate use of visitor pattern.
Exercise:
1) Differentiate between
d) Class and object
e) Generalization and specialization
f) Superclass and subclass
g) Dynamic and structural diagrams
2) List and explain the following
- Three dynamic UML diagrams
- Three structural UML diagrams
3) Choose a system of your choice and do the following
- Draw the class diagram
- Draw the sequence diagram
- Draw the use case diagram
4) List and explain 4 design patterns
71