Lab Manual_CS 606_Skill Development Lab_Jan-June23
Lab Manual_CS 606_Skill Development Lab_Jan-June23
LAB MANUAL
This manual is intended for the Third Year students of Computer Science and Engineering in
the subject of Design Pattern. This manual typically contains practical/Lab Sessions related
to the subject to enhance understanding.
The time spent on getting the design right before you start programming will almost always
save you time in the end. It's much, much easier to make major changes on a design, which is
after all just squiggly lines on paper, and then it is to make changes in hundreds or thousands
of lines of code.
The design process is typically split into distinct phases: Object Oriented Design (OOD) and
Design Pattern.
Students are advised to thoroughly go through this manual rather than only topics mentioned
in the syllabus as practical aspects are the key to understanding and conceptual visualization
of theoretical aspects covered in the books.
1. Make entry in the Log Book as soon as you enter the Laboratory.
2. All the students should sit according to their roll numbers starting
from their left to right.
3. All the students are supposed to enter the terminal number in the log book.
2. Students should be taught for taking the printouts under the observation
of lab teacher.
CEO
1 Understand the basics of software development life cycle as a product.
Course Outcomes
Upon completion of this subject / course the student will be able:
Specify, classify, implement, analyze and develop applications using
CO1 various SDLC models like Linear sequential, prototype, Evolutionary
models
Understand, classify, analyze and develop applications using Various
CO2
software standards. .
Understand, classify, implement various types of design patterns
CO3 (Creational, Behavioural, structural); understand and analyze each design
pattern using java program
Understand, classify, implement various types of design patterns
CO4 (Presentation layer, Integration layer, business layer ); Analyze the
problem statement make UML diagram and code the program in java .
Able to describe the SDLC, design patterns and software standards
CO5
applicable to the existing software systems.
ACROPOLIS INSTITUTE OF TECHNOLOGY & RESEARCH, INDORE
DEPARTMENT OF COMPUTER SCIENCE
3 Modeling UML Use Case Diagrams and Capturing Use Case Scenarios
Experiment 1
Identifying the requirements from problem statements
Introduction:
Requirements identification is the first step of any software development project. Until the requirements of a client
have been clearly identified, and verified, no other task (design, coding, testing) could begin. Usually business analysts
having domain knowledge on the subject matter discuss with clients and decide what features are to be
implemented.
Theory:
Requirements:
The software requirements are description of features and functionalities of the target system. Requirements convey
the expectations of users from the software product. The requirements can be obvious or hidden, known or
unknown, expected or unexpected from client’s point of view.
ACROPOLIS INSTITUTE OF TECHNOLOGY & RESEARCH, INDORE
DEPARTMENT OF COMPUTER SCIENCE
Characteristics of Requirements
Requirements gathered for any new system to be developed should exhibit the following three properties:
● Unambiguity: There should not be any ambiguity what a system to be developed should do. For example,
consider you are developing a web application for your client. The client requires that enough number of
people should be able to access the application simultaneously. What's the "enough number of people"? That
could mean 10 to you, but, perhaps, 100 to the client. There's an ambiguity.
● Consistency:The key point about consistency is that no requirement contradicts what another says. Paths
though the system must not process the same input differently. This can occur due the paths being written by
separated teams, and they not having agreed what should be done.
● Completeness:Each requirement must fully describe the functionality to be delivered. It must contain all the
information necessary for the developer to design and implement that bit of functionality.
Categorization of Requirements
Based on the target audience or subject matter, requirements can be classified into different types, as stated below:
● User requirements: They are written in natural language so that both customers can verify their requirements
have been correctly identified
● System requirements: They are written involving technical terms and/or specifications, and are meant for the
development or testing teams
Requirements can be classified into two groups based on what they describe:
● Functional requirements (FRs): These describe the functionality of a system -- how a system should react to a
particular set of inputs and what should be the corresponding output.
● Non-functional requirements (NFRs): They are not directly related what functionalities are expected from the
system. However, NFRs could typically define how the system should behave under certain situations. For
example, a NFR could say that the system should work with 128MB RAM. Under such condition, a NFR could
be more critical than a FR.
Non-functional requirements could be further classified into different types like:
● Product requirements: For example, a specification that the web application should use only plain HTML, and
no frames
● Performance requirements: For example, the system should remain available 24x7
● Organizational requirements: The development process should comply to SEI CMM level 4
Functional Requirements
Identifying Functional Requirements
Given a problem statement, the functional requirements could be identified by focusing on the following points:
● Identify the high level functional requirements simply from the conceptual understanding of the problem. For
example, a Library Management System, apart from anything else, should be able to issue and return books.
● Identify the cases where an end user gets some meaningful work done by using the system. For example, in a
digital library a user might use the "Search Book" functionality to obtain information about the books of his
interest.
● If we consider the system as a black box, there would be some inputs to it, and some output in return. This
black box defines the functionalities of the system.
ACROPOLIS INSTITUTE OF TECHNOLOGY & RESEARCH, INDORE
● For example, to search for a book,DEPARTMENT OFbook
user gives title of the COMPUTER
as input and SCIENCE
get the book details and location as
the output.
● Any high level requirement identified could have different sub-requirements. For example, "Issue Book"
module could behave differently for different class of users, or for a particular user who has issued the book
thrice consecutively.
Examples
A system may be required to present the user with a display of the number of records in a database. This is a
functional requirement. How up-to-date [update] this number needs to be, is a non-functional requirement. If the
number needs to be updated in real time, the system architects must ensure that the system is capable of updating
the [displayed] record count within an acceptably short interval of the number of records changing.
ACROPOLIS INSTITUTE OF TECHNOLOGY & RESEARCH, INDORE
DEPARTMENT OF COMPUTER SCIENCE
Experiment 2
Estimation of Project Metrics
Introduction:
After gathering the entire requirements specific to software project usually we need to think about different solution
strategy for the project. Expert business analysts are analyzing their benefits and as well as their shortcomings by
means of cost, time and resources require to develop it.
Theory:
Here we will focus on two methods for estimating project metrics: COCOMO and Halstead's method.
COCOMO
COCOMO (Constructive Cost Model) was proposed by Boehm. According to him, there could be three
categories of software projects: organic, semidetached, and embedded. The classification is done considering the
characteristics of the software, the development team and environment. These product classes typically
correspond to application, utility and system programs, respectively. Data processing programs could be
considered as application programs. Compilers, linkers, are examples of utility programs. Operating systems, real-
time system programs are examples of system programs. One could easily apprehend that it would take much
more time and effort to develop an OS than an attendance management system.
The concept of organic, semidetached, and embedded systems are described below.
Organic: A development project is said to be of organic type, if
● The project deals with developing a well understood application
● The development team is small
● The team members have prior experience in working with similar types of projects
Ratings
Ver
Very Nomina y
Cost Drivers Low Low l High High Extra High
Product attributes
Required software
0.75 0.88 1.00 1.15 1.40
reliability
Size of application
0.94 1.00 1.08 1.16
database
Complexity of the 0.70 0.85 1.00 1.15 1.30 1.65
ACROPOLIS INSTITUTE OF TECHNOLOGY & RESEARCH, INDORE
DEPARTMENT OFRatings
COMPUTER SCIENCE
Ver
Very Nomina y
Cost Drivers Low Low l High High Extra High
product
Hardware attributes
Run-time performance
1.00 1.11 1.30 1.66
constraints
Memory constraints 1.00 1.06 1.21 1.56
Volatility of the virtual
0.87 1.00 1.15 1.30
machine environment
Required turnabout
0.87 1.00 1.07 1.15
time
Personnel attributes
Analyst capability 1.46 1.19 1.00 0.86 0.71
Applications
1.29 1.13 1.00 0.91 0.82
experience
Software engineer
1.42 1.17 1.00 0.86 0.70
capability
Virtual machine
1.21 1.10 1.00 0.90
experience
Programming language
1.14 1.07 1.00 0.95
experience
Project attributes
Application of software
1.24 1.10 1.00 0.91 0.82
engineering methods
Use of software tools 1.24 1.10 1.00 0.91 0.83
Required development
1.23 1.08 1.00 1.04 1.10
schedule
c
Effort|corrected = Effort * EAF Tdev|corrected = 2.5 * (Effort| corrected)
Modeling UML Use Case Diagrams and Capturing Use Case Scenarios
Introduction
Use case diagram is a platform that can provide a common understanding for the end-users, developers and
the domain experts. It is used to capture the basic functionality i.e. use cases, and the users of those available
functionality, i.e. actors, from a given problem statement.
In this experiment, we will learn how use cases and actors can be captured and how different use cases are
related in a system.
Theory:
Actor
An actor can be defined as an object or set of objects, external to the system, which interacts with the system
to get some meaningful work done. Actors could be human, devices, or even other systems.
For example, consider the case where a customer withdraws cash from an ATM. Here, customer is a human
actor.
Primary actor: They are principal users of the system, who fulfill their goal by availing some service from the
system. For example, a customer uses an ATM to withdraw cash when he needs it. A customer is the primary
actor here.
Supporting actor: They render some kind of service to the system. "Bank representatives", who replenishes
the stock of cash, is such an example. It may be noted that replenishing stock of cash in an ATM is not the prime
functionality of an ATM.
In a use case diagram primary actor are usually drawn on the top left side of the diagram.
Use Case
A use case is simply a functionality provided by a system.
Continuing with the example of the ATM, withdraw cash is a functionality that the ATM provides. Therefore,
this is a use case. Other possible use cases include, check balance, change PIN, and so on.
Use cases include both successful and unsuccessful scenarios of user interactions with the system. For
example, authentication of a customer by the ATM would fail if he enters wrong PIN. In such case, an error
message is displayed on the screen of the ATM.
Subject
ACROPOLIS INSTITUTE OF TECHNOLOGY & RESEARCH, INDORE
Subject is simplythe system under DEPARTMENT
consideration. UseOFcases
COMPUTER SCIENCE
apply to a subject. For example, an ATM is a
subject, having multiple use cases, and multiple actors interact with it. However, one should be careful of external
systems interacting with the subject as actors.
Graphical Representation
An actor is represented by a stick figure and name of the actor is written below it. A use case is depicted by an
ellipse and name of the use case is written inside it. The subject is shown by drawing a rectangle. Label for the
system could be put inside it. Use cases are drawn inside the rectangle, and actors are drawn outside the
rectangle, as shown in figure.
An actor must be associated with at least one-use case. Similarly, a given use case must be associated with at
least one actor. Association among the actors are usually not shown. However, one can depict the class hierarchy
among actors.
Include relationship
Extend relationship
Use case generalization
Include Relationship
Include relationships are used to depict common behaviour that are shared by multiple use cases. This could
be considered analogous to writing functions in a program in order to avoid repetition of writing the same code.
Such a function would be called from different points within the program.
Include relationship is depicted by a dashed arrow with a «include» stereotype from the including use case to
the included use case.
Extend Relationship
Use case extensions are used used to depict any variation to an existing use case. They are used to the specify
the changes required when any assumption made by the existing use case becomes false [iv, v].
Notation
Extend relationship is depicted by a dashed arrow with a «extend» stereotype from the extending use case to
the extended use case.
ACROPOLIS INSTITUTE OF TECHNOLOGY & RESEARCH, INDORE
DEPARTMENT OF COMPUTER SCIENCE
Generalization Relationship
Generalization relationship are used to represent the inheritance between use cases. A derived use case
specializes some functionality it has already inherited from the base use case.
Notation
Generalization relationship is depicted by a solid arrow from the specialized (derived) use case to the more
generalized (base) use case.
Following general guidelines could be kept in mind while trying to draw a use case diagram:
Use cases identified should let some meaningful work done by the actors
Associate the actors and use cases -- there shouldn't be any actor or use case floating without any connection
ACROPOLIS INSTITUTE OF TECHNOLOGY & RESEARCH, INDORE
DEPARTMENT OF COMPUTER SCIENCE
EXPERIMENT4
E-R Modeling from the Problem Statements
Introduction:
Developing databases is a very important task to develop a system. Before going to form exact database tables and
establishing relationships between them, we conceptually or logically can model our database using ER diagrams.
Theory:
Attributes of Entity
Attributes are the characteristics describing any entity belonging to an entity set. Any entity in a set can be described
by zero or more attributes.
For example, any student has got a name, age, an address. At any given time a student can study only at one school.
In the school he would have a roll number, and of course a grade in which he studies. These data are the attributes of
the entity set Student.
Keys
One or more attribute(s) of an entity set can be used to define the following keys:
● Super key: A super key is a set of one or more attributes (columns), which can uniquely identify a row in
a table. For example, a school can have any number of students. However, if we know grade and roll
number, then we can uniquely identify a student in that school.
● Candidate key: It is a minimal subset of a super key.
● Primary key: A database might have more than one candidate key. Any candidate key chosen for a
particular implementation of the database is called a primary key.
● Prime attribute: Any attribute taking part in a super key
Weak Entity
A weak entity set is an entity set that does not contain sufficient attributes to uniquely identify its entities. In
other words, a primary key does not exist for a weak entity set.
For example, consider a company that allows employees to have travel allowance for their immediate family.
So, here we have two entity sets: employee and family, related by "Can claim for". However, family doesn't have a
ACROPOLIS INSTITUTE OF TECHNOLOGY & RESEARCH, INDORE
DEPARTMENT
super key. Existence of a family is entirely dependent on OF
the COMPUTER SCIENCE
concerned employee. So, it is meaningful only with
reference to employee.
Mapping Cardinalities
One of the main tasks of ER modeling is to associate different entity sets. Let's consider two entity sets E1 and
E2 associated by a relationship set R. Based on the number of entities in E1 and E2 are associated with, we can
have the following four type of mappings:
● One to one: An entity in E1 is related to at most a single entity in E2, and vice versa
● One to many: An entity in E1 could be related to zero or more entities in E2. Any entity in E2 could be related
to at most a single entity in E1.
● Many to one: Zero or more number of entities in E1 could be associated to a single entity in E2. However, an
entity in E2 could be related to at most one entity in E1.
● Many to many: Any number of entities could be related to any number of entities in E2, including zero, and
vice versa.
Entity with
Roll is the primary
attributes
key; denoted with
an underline
Weak
entity set
Name of the
Relationshi relationship is
p set written inside the
diamond
Related
enity sets
ACROPOLIS INSTITUTE OF TECHNOLOGY & RESEARCH, INDORE
Term Notation DEPARTMENT OF COMPUTER SCIENCE
Remarks
A person can own
zero or more cars
Relationshi
but no two
p cardinality
persons can own
the same car
Relationshi
p with weak
entity set
Importance of ER modeling
.
Steps to implem
RDBMS
Given a problem statement, the first step is to identify the entities, attributes and relationships. We represent
them using an ER diagram. Using this ER diagram, table structures are created, along with required constraints.
Finally, these tables are normalized in order to remove redundancy and maintain data integrity. Thus, to have
data stored efficiently, the ER diagram is to be drawn as much detailed and accurate as possible.
ACROPOLIS INSTITUTE OF TECHNOLOGY & RESEARCH, INDORE
DEPARTMENT OF COMPUTER
EXPERIMENT 5 SCIENCE
Modeling UML Class Diagrams and Sequence Diagrams
Introduction:
Classes are the structural units in object oriented system design approach, so it is essential to know all the
relationships that exist between the classes, in a system. All objects in a system are also interacting to each other by
means of passing messages from one object to another. Sequence diagram shows these interactions with time
ordering of the messages.
In this Experiment, we will learn about the representation of class diagram and sequence diagram. We also learn
about different relationships that exist among the classes, in a system.
Theory:
Developing a software system in object oriented approach is very much dependent on understanding the problem.
Some aspects and the respective models are used to describe problems and in context of those aspects the respective
models give a clear idea regarding the problem to a designer. For developer, structural and behavioral aspects are
two key aspects to see through a problem to design a solution for the same.
Class diagram:
Class diagram contains the system classes with its data members, operations and relationships between classes.
Class:
A set of objects containing similar data members and member functions is described by a class. In UML syntax, class is
identified by solid outline rectangle with three compartments which contain
● Class name
A class is uniquely identified in a system by its name. A textual string is taken as class name. It lies in the first
compartment in class rectangle.
● Attributes
Property shared by all instances of a class. It lies in the second compartment in class rectangle.
● Operations
An execution of an action can be performed for any object of a class. It lies in the last compartment in class
rectangle.
Example
ACROPOLIS INSTITUTE OF TECHNOLOGY & RESEARCH, INDORE
DEPARTMENT
To build a structural model for an Educational OF COMPUTER
Organization, ‘Course’ can beSCIENCE
treated as a class which contains
attributes ‘courseName’ & ‘courseID’ with the operations ‘addCourse()’ & ‘removeCourse()’ allowed to be
performed for any object to that class.
Figure-01:
● Generalization/Specialization
It describes how one class is derived from another class. Derived class inherits the properties of its parent class.
Example
Figure-02:
Geometric Shapes is the class that describes how many sides a particular shape has. Triangle, Quadrilateral and
Pentagon are the classes that inherit the property of the Geometric Shapes class. So the relations among these
classes are generalization. Now Equilateral Triangle, Isosceles Triangle and Scalene Triangle, all these three
classes inherit the properties of Triangle class as each one of them has three sides. So, these are specialization of
Triangle class.
Relationships:
Existing relationships in a system describe legitimate connections between the classes in that system.
● Association
It is an instance level relationship that allows exchanging messages among the objects of both ends of
association. A simple straight line connecting two class boxes represent an association. We can give a name to
association and also at the both end we may indicate role names and multiplicity of the adjacent classes.
Association may be uni-directional.
Example
In structure model for a system of an organization an employee (instance of ‘Employee’ class) is always assigned
to a particular department (instance of ‘Department’ class) and the association can be shown by a line
connecting the respective classes.
Figure-03:
● Aggregation
ACROPOLIS INSTITUTE OF TECHNOLOGY & RESEARCH, INDORE
DEPARTMENT
It is a special form of association which OF COMPUTER
describes a part-whole SCIENCE
relationship between a pair of classes. It means,
in a relationship, when a class holds some instances of related class, then that relationship can be designed as an
aggregation.
Example
For a supermarket in a city, each branch runs some of the departments they have. So, the relation among the
classes ‘Branch’ and ‘Department’ can be designed as an aggregation. In UML, it can be shown as in the fig.
below
Figure-04:
● Composition
It is a strong from of aggregation which describes that whole is completely owns its part. Life cycle of the part
depends on the whole.
Example
Let consider a shopping mall has several branches in different locations in a city. The existence of branches
completely depends on the shopping mall as if it is not exist any branch of it will no longer exists in the city. This
relation can be described as composition and can be shown as below
Figure-05:
● Multiplicity
It describes how many numbers of instances of one class is related to the number of instances of another class in
an association.
Notation for different types of multiplicity:
Figure-06:
Example
One vehicle may have two or more wheels
Figure-07:
ACROPOLIS INSTITUTE OF TECHNOLOGY & RESEARCH, INDORE
DEPARTMENT OF COMPUTER SCIENCE
Sequence diagram
It represents the behavioral aspects of a system. Sequence diagram shows the interactions between the objects by
means of passing messages from one object to another with respect to time in a system.
Elements in sequence diagram
Sequence diagram contains the objects of a system and their life-line bar and the messages passing between them.
Object
Objects appear at the top portion of sequence diagram. Object is shown in a rectangle box. Name of object precedes
a colon ‘:’ and the class name, from which the object is instantiated. The whole string is underlined and appears in a
rectangle box. Also, we may use only class name or only instance name.
Objects which are created at the time of execution of use case and are involved in message passing , are appear in
diagram, at the point of their creation.
Life-line bar
A down-ward vertical line from object-box is shown as the life-line of the object. A rectangle bar on life-line indicates
that it is active at that point of time.
Messages
Messages are shown as an arrow from the life-line of sender object to the life-line of receiver object and labeled with
the message name. Chronological order of the messages passing throughout the objects’ life-line show the sequence
in which they occur. There may exist some different types of messages:
● Synchronous messages: Receiver start processing the message after receiving it and sender needs to wait until
it is made. A straight arrow with close and fill arrow-head from sender life-line bar to receiver end, represent a
synchronous message.
● Asynchronous messages: For asynchronous message sender needs not to wait for the receiver to process the
message. A function call that creates thread can be represented as an asynchronous message in sequence
diagram. A straight arrow with open arrow-head from sender life-line bar to receiver end, represent an
asynchronous message.
● Return message: For a function call when we need to return a value to the object, from which it was called,
then we use return message. But, it is optional, and we are using it when we are going to model our system in
much detail. A dashed arrow with open arrow-head from sender life-line bar to receiver end, represent that
message.
● Response message: One object can send a message to self. We use this message when we need to show the
interaction between the same object.
Figure-08:
ACROPOLIS INSTITUTE OF TECHNOLOGY & RESEARCH, INDORE
DEPARTMENT OF COMPUTER SCIENCE
EXPERIMENT 6
Introduction to Design patterns. Describe the organization of catalog along with the following
design patterns.
a. Creational Patterns.
b. Structural Patterns.
c. Behavioral Patterns.
Theory:
Design patterns describe the relations and interactions of different class or objects or types. They
do not specify the final class or types that will be used in any software code, but give an abstract
view of the solution. Patterns show us how to build systems with good object-oriented design
qualities by reusing successful designs and architectures. Expressing proven techniques speed up
the development process and make the design patterns, more accessible to developers of new
ACROPOLIS INSTITUTE OF TECHNOLOGY & RESEARCH, INDORE
system. DEPARTMENT OF COMPUTER SCIENCE
Good object-oriented software design requires considering issues that may not become visible
until later in the implementation. Reusing design patterns helps to prevent subtle issues that can
cause major problems, and it also improves code readability for coders and architects who are
familiar with the patterns and we can also avoid alternatives that compromise reusability.
These patterns are also called as GOF patterns (Gang-Of-Four). Their names are listed in the
table given below.
o Behavioural patterns characterize the ways in which classes and objects interact
and distribute responsibility.
o Scope, which specifies whether the pattern applies primarily to classes or to objects:
The following table shows the classification of design patterns. Note, that those are the patterns
introduced by the Gang of Four.
Prototype Object
Singleton Object
Structural Adapter Class
ACROPOLIS INSTITUTE OF TECHNOLOGY & RESEARCH, INDORE
Bridge DEPARTMENT OF COMPUTERObject
SCIENCE
State Object
Strategy Object
Visitor Object
Creational patterns
Creational design patterns abstract the instantiation process. They help make a system
independent of how its objects are created, composed, and represented.
A class creational pattern uses inheritance to vary the class that’s instantiated, whereas an object
creational pattern will delegate instantiation to another object.
The creational design patterns allow configuring of a software system as a system with
―product‖ objects that vary widely in structure and functionality. Such configuration can be
static, i.e., specified at compile-time, or dynamic, i.e., specified at run-time.
In software engineering, creational design patterns are design patterns that deal with object
creation mechanisms, trying to create objects in a manner suitable to the situation. The basic
form of object creation could result in design problems or added complexity to the design.
Creational design patterns solve this problem by somehow controlling this object creation.
o Abstract Factory
Creates an instance of several families of classes
o Builder
Separates object construction from its representation
o Factory Method
Creates an instance of several derived classes
o Object Pool
Avoid expensive acquisition and release of resources by recycling objects that are no
longer in use
ACROPOLIS INSTITUTE OF TECHNOLOGY & RESEARCH, INDORE
DEPARTMENT OF COMPUTER SCIENCE
o Prototype
A fully initialized instance to be copied or cloned
o Singleton
A class of which only a single instance can exist
Structural patterns are concerned with how classes and objects are composed to form larger
structures.
Structural class patterns use inheritance to compose interfaces or implementations. For example,
multiple inheritance can be seen as a kind of structural design patterns, since it uses inheritance
to mix two or more classes into a new one.
Rather than composing interfaces or implementations, structural object patterns describe ways to
compose objects to realize new functionality. The added flexibility of object composition comes
from the ability to change the composition at run-time, which is impossible with static class
composition.
This design patterns is all about Class and Object composition. Structural class-creation
patterns use inheritance to compose interfaces. Structural object-patterns define ways to
compose objects to obtain new functionality.
o Adapter
o Bridge
Separates an object’s interface from its implementation
o Composite
A tree structure of simple and composite objects
o Decorator
Add responsibilities to objects dynamically
o Facade
A single class that represents an entire subsystem
o Flyweight
ACROPOLIS INSTITUTE OF TECHNOLOGY & RESEARCH, INDORE
A fine-grained instanceDEPARTMENT OF COMPUTER
used for efficient sharing SCIENCE
o Private Class Data
Restricts accessor/mutator access
o Proxy
An object representing another object
Behavioral patterns are concerned with algorithms and the assignment of responsibility between
objects. Behavioural patterns describe not just patterns of objects or classes but also the patterns
of communication between them. These patterns characterize complex control flow that is
difficult to follow at run-time. They shift your focus away from flow of control to let you
concentrate just on the way objects are interconnected.
Behavioral object patterns use object composition rather than inheritance. For example, a
behavioral object pattern can describe how a group of object might cooperate to perform a task
that no single object can carry out by itself. A typical example is the Observer pattern from the
Smalltalk (Model/View/Controller paradigm). Views are used to show the state of data
(contained in Model) and they are observers of this data. Whenever a model changes its state all
views are notified and they can update the representation of the data in views.
This design patterns is all about Class's objects communication. Behavioral patterns are those
patterns that are most specifically concerned with communication between objects.
o Chain of responsibility
A way of passing a request between a chain of objects
o Command
Encapsulate a command request as an object
o Interpreter
A way to include language elements in a program
o Iterator
Sequentially access the elements of a collection
o Mediator
Defines simplified communication between classes
o Memento
ACROPOLIS INSTITUTE OF TECHNOLOGY & RESEARCH, INDORE
DEPARTMENT
Capture and restore an object's internal stateOF COMPUTER SCIENCE
o Null Object
Designed to act as a default value of an object
o Observer
A way of notifying change to a number of classes
o State
o Strategy
Encapsulates an algorithm inside a class
o Template method
Defer the exact steps of an algorithm to a subclass
o Visitor
Conclusion:
Thus we, have studied organization of catalog along with all design patterns successfully.
EXPERIMENT 7
Write a program to implement the following concepts in java.
a. Method overriding.
b. Interface.
c. Abstract class.
Theory:
● Method Overriding: Declaring a method in sub class which is already present in parent
class is known as method overriding. Overriding is done so that a child class can give its
ACROPOLIS INSTITUTE OF TECHNOLOGY & RESEARCH, INDORE
own implementation toDEPARTMENT
a method which isOF COMPUTER
already provided bySCIENCE
the parent class. In this
case the method in parent class is called overridden method and the method in child
class is called overriding method.
Lets take a simple example to understand this. We have two classes: A child class Boy
and a parent class Human. The Boy class extends Human class. Both the classes have a
common method void eat(). Boy class is giving its own implementation to the
eat() method or in other words it is overriding the eat() method.
The purpose of Method Overriding is clear here. Child class wants to give its own
implementation so that when it calls this method, it prints Boy is eating instead of Human
is eating.
Sample Code:
class Human{
//Overridden method
{
System.out.println("Human is eating");
}
}
//Overriding method
obj.eat();
} public void eat()
} { System.out.println("Boy is
}
public static void main( String
args[]) { Boy obj = new Boy();
//This will call the child class version of eat()
Output: Boy is eating.
Interface:
The interface in java is a mechanism to achieve abstraction. There can be only abstract
methods in the java interface not method body. It is used to achieve abstraction and multiple
inheritance in Java. It cannot be instantiated just like abstract class.
ACROPOLIS INSTITUTE OF TECHNOLOGY & RESEARCH, INDORE
DEPARTMENT OF COMPUTER SCIENCE
Why use Java interface?
There are mainly three reasons to use interface. They are given below.
Sample Code:
interface printable{
void print();
obj.print();
Output: Hello
● Abstract Class:
Abstraction is a process of hiding the implementation details and showing only functionality to
the user.
Another way, it shows only important things to the user and hides the internal details for
example sending sms, you just type the text and send the message. You don't know the internal
processing about the message delivery.
Abstraction lets you focus on what the object does instead of how it does it.
ACROPOLIS INSTITUTE OF TECHNOLOGY & RESEARCH, INDORE
DEPARTMENT
A class that is declared as abstract OF COMPUTER
is known as abstract class. It needs toSCIENCE
be extended and its
method implemented. It cannot be instantiated.
abstract method
A method that is declared as abstract and does not have implementation is known as abstract
method.
Sample Code:
obj.run();
EXPERIMENT 8
a. Aim: Write a Program to implement Factory pattern.
Theory:
• Defines an interface for creating objects but let sub-classes decide which of those
instantiate.
• Enables the creator to defer Product creation to a sub-class.
• Factory pattern is one of the most used design pattern in Java. This type of design
ACROPOLIS INSTITUTE OF TECHNOLOGY & RESEARCH, INDORE
DEPARTMENT
pattern comes under creational pattern as OF
this COMPUTER
pattern providesSCIENCE
one of the best ways to
create an object.
• In Factory pattern, we create object without exposing the creation logic to the client and
refer to newly created object using a common interface.
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.
• Virtual Constructor .
Applicability:
· classes delegate responsibility to one of several helper subclasses, and you want to
localize the knowledge of which helper subclass is the delegate.
CLASS DIAGRAM :
Sample code:
Step 1
Create an interface.
ACROPOLIS INSTITUTE OF TECHNOLOGY & RESEARCH, INDORE
Shape.java DEPARTMENT OF COMPUTER SCIENCE
public interface
Shape { void draw();
}
Step 2
Create concrete classes implementing the same interface.
Rectangle.java
@Override
public void draw() {
System.out.println("Inside Rectangle::draw() method.");
}
}
Square.java
@Override
public void draw() {
System.out.println("Inside Square::draw() method.");
}
}
Circle.java
Step 3
DEPARTMENT OF COMPUTER SCIENCE
Create a Factory to generate object of concrete class based on given information.
ShapeFactory.java
return
public null;
class ShapeFactory {
}
//use getShape method to get object of type shape
if(shapeType.equalsIgnoreCase("CIRCLE")){
public
return new Shape getShape(String shapeType){
Circle();
if(shapeType == null){
return null;
} else if(shapeType.equalsIgnoreCase("RECTANGLE"))
{ return new Rectangle();
} else if(shapeType.equalsIgnoreCase("SQUARE"))
{ return new Square();
}
return null;
}
}
Step 4
Use the Factory to get object of concrete class by passing an information such as type.
FactoryPatternDemo.java
shape1.draw();
DEPARTMENT OF COMPUTER SCIENCE
Step 5
Theory:
• Abstract Factory patterns works around a super-factory which creates other factories.
This factory is also called as Factory of factories. This type of design pattern comes
under creational pattern as this pattern provides one of the best ways to create an
object.
Intent:
Provide an interface for creating families of related or dependent objects without specifying
their concrete classes.
Applicability:
· a system should be independent of how its products are created, composed, and represented.
· a family of related product objects is designed to be used together, and you need to enforce
this constraint.
· you want to provide a class library of products, and you want to reveal just their interfaces,
not their implementations.
ACROPOLIS INSTITUTE OF TECHNOLOGY & RESEARCH, INDORE
DEPARTMENT OF COMPUTER SCIENCE
Class Diagram:
Sample Code:
Step 1
Create an interface for Shapes.
Shape.java
public interface
Shape { void draw();
}
Step 2
Create concrete classes implementing the same interface.
Rectangle.java
@Override
public void draw() {
System.out.println("Inside Rectangle::draw() method.");
}
}
Square.java
@Override
public void draw() {
System.out.println("Inside Square::draw() method.");
}
}
Circle.java
@Override
public void draw() {
System.out.println("Inside Circle::draw() method.");
}
}
Step 3
Create an interface for Colors.
Color.java
Step4
Create concrete classes implementing the same interface.
Red.java
@Override
public void fill() {
System.out.println("Inside Red::fill() method.");
}
}
Green.java
Blue.java
@Override
public void fill() {
System.out.println("Inside Blue::fill() method.");
}
}
ACROPOLIS INSTITUTE OF TECHNOLOGY & RESEARCH, INDORE
DEPARTMENT OF COMPUTER SCIENCE
Step 5
Create an Abstract class to get factories for Color and Shape Objects.
AbstractFactory.java
Step 6
Create Factory classes extending AbstractFactory to generate object of concrete class based on
given information.
ShapeFactory.java
@Override
public Shape getShape(String shapeType){
if(shapeType ==
null){ return null;
}
if(shapeType.equalsIgnoreCase("CIRCLE
")){ return new Circle();
}else
if(shapeType.equalsIgnoreCase("RECTANGLE")){
return new Rectangle();
}else if(shapeType.equalsIgnoreCase("SQUARE")){
ACROPOLIS INSTITUTE OF TECHNOLOGY & RESEARCH, INDORE
DEPARTMENT OF COMPUTER SCIENCE
return null;
}
@Override
Color getColor(String
color) { return null;
}
ColorFactory.java
@Override
public Shape getShape(String
shapeType){ return null;
}
@Override
Color getColor(String color) {
if(color ==
null){ return
null;
}
ACROPOLIS INSTITUTE OF TECHNOLOGY & RESEARCH, INDORE
DEPARTMENT OF COMPUTER SCIENCE
if(color.equalsIgnoreCase("RE
D")){ return new Red();
}else
if(color.equalsIgnoreCase("GREEN"
)){ return new Green();
}else
if(color.equalsIgnoreCase("BLUE")){
return new Blue();
}
return null;
Step 7
Create a Factory generator/producer class to get factories by passing an information such as
Shape or Color
FactoryProducer.java
if(choice.equalsIgnoreCase("SHA
PE")){ return new ShapeFactory();
}else
if(choice.equalsIgnoreCase("COLOR")){
return new ColorFactory();
}
return null;
ACROPOLIS INSTITUTE OF TECHNOLOGY & RESEARCH, INDORE
DEPARTMENT OF COMPUTER SCIENCE
}
}
Step 8
Use the FactoryProducer to get AbstractFactory in order to get factories of concrete classes by
passing an information such as type.
AbstractFactoryPatternDemo.java
public class
AbstractFactoryPatternDemo { public
static void main(String[] args) {
Step 9
Verify the output.
Conclusion :
Thus we have executed programs for factory pattern and abstract factory successfully.
EXPERIMENT 9
Theory:
• Singleton pattern is one of the simplest design patterns in Java. This type of design
pattern comes under creational pattern as this pattern provides one of the best way to
create an object.
• This pattern involves a single class which is responsible to creates own object while
making sure that only single object get created. This class provides a way to access its
only object which can be accessed directly without need to instantiate the object of the
class. Enables the creator to defer Product creation to a sub-class.
– Private constructor
– Global access
• Intent
Ensure a class has only one instance, and provide a global point of access to it.
Applicability:
• there must be exactly one instance of a class, and it must be accessible to clients from a
well-known access point.
• when the sole instance should be extensible by subclassing, and clients should be able
to use an extended instance without modifying their code.
Class Diagram:
Sample Code:
Step 1
Create a Singleton Class.
SingleObject.java
Step 2
Get the only object from the singleton class.
SingletonPatternDemo.java
//illegal construct
//Compile Time Error: The constructor SingleObject() is not visible
//SingleObject object = new SingleObject();
Step 3
Verify the output.
Hello World!
b. Aim: Write a Program to implement Composite design pattern.
Theory:
• 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 hierarchies.
• This type of design pattern comes under structural pattern as this pattern creates a tree
structure of group of objects.
• This pattern creates a class contains group of its own objects. This class provides ways to
modify its group of same objects.
• We are demonstrating use of Composite pattern via following example in which show
employees hierarchy of an organization.
• Intent
• Applicability
• you want clients to be able to ignore the difference between compositions of objects
and individual objects. Clients will treat all objects in the composite structure uniformly.
Class Diagram:
Sample Code:
Step 1
Create Employee class having list of Employee objects.
Employee.java
import java.util.ArrayList;
import java.util.List;
public class
Employee { private
String name; private
String dept; private int
salary;
private List<Employee> subordinates;
// constructor
public Employee(String name,String dept, int
sal) { this.name = name;
this.dept = dept;
this.salary = sal;
subordinates = new ArrayList<Employee>();
}
public List<Employee>
getSubordinates(){ return
subordinates;
}
Step 2
Use the Employee class to create and print employee hierarchy.
CompositePatternDemo.java
CEO.add(headSales);
CEO.add(headMarketin
g);
headSales.add(salesExecutive
1);
headSales.add(salesExecutive
2);
headMarketing.add(clerk1);
headMarketing.add(clerk2);
salary :20000 ]
Employee :[ Name : Richard, dept : Sales,
salary :10000 ]
salary :10000 ]
Conclusion:
Theory:
The IT Environment With over 50,000 physical servers, a growing private cloud environment
(VMware vSphere, Microsoft HyperV, IBM PowerVM), and hundreds of storage arrays (EMC
Symmetrix, HDS, netApp), managing IT operations at this large bank is no small feat. More than
1,600 IT engineers in over a dozen datacenters worldwide work closely with 3rd party partners
and vendors to meet the bank’s service availability goals.
Challenges:
With millions of customers accessing the bank systems daily at ATMs, branches, online, and
through multiple call centers, any downtime or service disruptions are practically unacceptable to
the bank. With a growing portion of customers relying on online and mobile banking, 24/7
service reliability has become more critical than ever. To address these needs, major efforts and
resources have been directed towards the creation of a robust high availability and disaster
recovery infrastructure. In this complex infrastructure comprising multiple datacenters,
configuration changes are undertaken daily by different groups in various parts of the
environment. While each team was making an effort to apply best practices in its own domain,
there was no visibility to the implications and risks introduced by such modifications on the
overall stability, service availability, and DR readiness of critical systems. As the IT environment
has grown in size and complexity, keeping production high availability and disaster recovery
systems in complete sync across IT teams and domains (e.g., server, storage, databases and
virtualization) has become an increasing challenge. Moreover, management was lacking
visibility into how well the organization was keeping up with established Service Level
Agreements (SLA’s) for availability (RTO), data protection (RPO), and retention objectives.
In Search of a Solution:
While overall service performance of the bank has been satisfactory, minor incidents over a
several month period have alerted the bank’s IT stewards to hidden vulnerabilities and the lack
of visibility to impending downtime and data loss risks. Although the bank managed to escape
these incidents without a major service impact, other banks were not so lucky. Publicized
outages at major financial institutions around the world caught the attention of senior
management. They were determined to avoid seeing their bank suffer similar embarrassment and
dire financial consequences. Following management’s directive, a committee was put in place to
define the requirements for a solution: Proactively detect risks introduced by configuration
changes across the entire datacenter and DR environments Analyze the potential impact of
such risks on service availability levels and disaster recovery readiness Help the relevant
teams pinpoint the source of each risk identified Provide management with a consolidated
view of downtime and data loss risks across the entire environment Measure adherence to
availability and data recovery SLA’s (RPO, RTO, redundancy, DR capacity) Simplify internal
and regulatory compliance reporting Improve DR capacity management and planning In
addition, the IT team mandated the solution must operate in a nonintrusive manner (preferably
agentless) and integrate with the service management system used by the organization.
Results :
Since the bank has implemented the AvailabilityGuard solution, downtime and data loss risks
have decreased by over 70%. AvailabilityGuard has also been helping the bank break down
many of the long-standing IT silos. AvailabilityGuard provides a unified platform that detects
availability risks across all IT domains, enabling collaboration among the various teams. And
since most issues are identified and resolved before they impact service availability, there is a
50% decrease in time spent on resolving emergency issues. With AvailabilityGuard well-
integrated into the bank’s IT infrastructure and processes, planning for the next phase of
implementation is underway, expanding the coverage of AvailabilityGuard to include all
production and DR systems.
Aim: Describe the Methods to analyze the complexity of design patterns.
Conclusion:
Thus ,we have studied Methods to analyze the complexity of design patterns.