Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
4 views

Lab Manual_CS 606_Skill Development Lab_Jan-June23

The document is a laboratory manual for third-year Computer Science and Engineering students at Acropolis Institute of Technology & Research, focusing on Design Patterns and practical sessions. It outlines the importance of design in software development, provides guidelines for laboratory conduct, and details course objectives and outcomes. Additionally, it includes a list of practical programs and experiments aimed at enhancing students' understanding of software requirements and project estimation techniques.

Uploaded by

Akshat sethi
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Lab Manual_CS 606_Skill Development Lab_Jan-June23

The document is a laboratory manual for third-year Computer Science and Engineering students at Acropolis Institute of Technology & Research, focusing on Design Patterns and practical sessions. It outlines the importance of design in software development, provides guidelines for laboratory conduct, and details course objectives and outcomes. Additionally, it includes a list of practical programs and experiments aimed at enhancing students' understanding of software requirements and project estimation techniques.

Uploaded by

Akshat sethi
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 63

ACROPOLIS INSTITUTE OF TECHNOLOGY & RESEARCH, INDORE

DEPARTMENT OF COMPUTER SCIENCE

LAB MANUAL

CS-606: Skill Development

B. Tech - Computer Science and Engineering


ACROPOLIS INSTITUTE OF TECHNOLOGY & RESEARCH, INDORE
DEPARTMENT OF COMPUTER SCIENCE

LABORATORY MANUAL CONTENTS

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.

Good Luck for your Enjoyable Laboratory Sessions


ACROPOLIS INSTITUTE OF TECHNOLOGY & RESEARCH, INDORE
DEPARTMENT OF COMPUTER SCIENCE

DOs and DON’Ts in Laboratory:

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.

4. Do not change the terminal on which you are working.

5. All the students are expected to get at least the algorithm


of the program/concept to be implemented.

6. Strictly observe the instructions given by the teacher/Lab Instructor.

Instruction for Laboratory Teachers::

1. Submission related to whatever lab work has been completed should


be done during the next lab session. The immediate arrangements for
printouts related to submission on the day of practical assignments.

2. Students should be taught for taking the printouts under the observation
of lab teacher.

3. The promptness of submission should be encouraged by way of marking


and evaluation patterns that will benefit the sincere students.
ACROPOLIS INSTITUTE OF TECHNOLOGY & RESEARCH, INDORE
DEPARTMENT OF COMPUTER SCIENCE

Vision of CSE Department

Mission of CSE Department

Program Educational Objectives (PEOs)


ACROPOLIS INSTITUTE OF TECHNOLOGY & RESEARCH, INDORE
DEPARTMENT OF COMPUTER SCIENCE

Program Specific Outcomes (PSOs)


ACROPOLIS INSTITUTE OF TECHNOLOGY & RESEARCH, INDORE
DEPARTMENT OF COMPUTER SCIENCE
Programme Outcomes (POs):
Engineering Graduates will be able to:
1. Engineering knowledge: Apply the knowledge of mathematics, science, engineering
fundamentals, and an engineering specialization to the solution of complex engineering
problems.
2. Problem analysis: Identify, formulate, review research literature, and analyze complex
engineering problems reaching substantiated conclusions using first principles of
mathematics, natural sciences, and engineering sciences.
3. Design/development of solutions: Design solutions for complex engineering problems
and design system components or processes that meet the specified needs with
appropriate consideration for the public health and safety, and the cultural, societal,
and environmental considerations.
4. Conduct investigations of complex problems: Use research-based knowledge and
research methods including design of experiments, analysis and interpretation of data,
and synthesis of the information to provide valid conclusions.
5. Modern tool usage: Create, select, and apply appropriate techniques, resources, and
modern engineering and IT tools including prediction and modeling to complex
engineering activities with an understanding of the limitations.
6. The engineer and society: Apply reasoning informed by the contextual knowledge to
assess societal, health, safety, legal and cultural issues and the consequent
responsibilities relevant to the professional engineering practice.
7. Environment and sustainability: Understand the impact of the professional engineering
solutionsi n societal and environmental contexts, and demonstrate the knowledge of,
and need for sustainable development.
8. Ethics: Apply ethical principles and commit to professional ethics and responsibilities
and norms of the engineering practice.
9. Individual and team work: Function effectively as an individual, and as a member or
leader in diverse teams, and in multidisciplinary settings.
10. Communication: Communicate effectively on complex engineering activities with the
engineering community and with society at large, such as, being able to comprehend
and write effective reports and design documentation, make effective presentations,
and give and receive clear instructions.
11. Project management and finance: Demonstrate knowledge and understanding of the
engineering and management principles and apply these to one’s own work, as a
member and leader in a team, to manage projects and in multidisciplinary
environments.
12. Life-long learning: Recognize the need for, and have the preparation and ability to
engage in independent and life-long learning in the broadest context of technological
change.
ACROPOLIS INSTITUTE OF TECHNOLOGY & RESEARCH, INDORE
DEPARTMENT OF COMPUTER SCIENCE
Course Educational Objectives

CEO
1 Understand the basics of software development life cycle as a product.

CEO Understand the current requirements of industries for software


2 standards
CEO
Implement the software as a product using different design patterns
3
CEO
Apply the software development techniques in real life applications.
4
CEO Understand the existing software solutions and correlate with the
5 SDLC, design patterns and software standards

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

CS-606: Skill Development


List of Programs:
S.No. Practical
1 Identifying the requirements from problem statements.

2 Estimation of Project Metrics

3 Modeling UML Use Case Diagrams and Capturing Use Case Scenarios

4 E-R Modeling from the Problem Statements

5 Modeling UML Class Diagrams and Sequence Diagrams

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.
7 Write a program to implement the following concepts in java.
ACROPOLIS INSTITUTE OF TECHNOLOGY & RESEARCH, INDORE
DEPARTMENT OF COMPUTER SCIENCE
a. Method overriding.
b. Interface.
c. Abstract class.
8 a. Write a Program to implement Factory pattern.
b. Write a program to implement abstract factory.
9 a. Write a Program to implement Singleton pattern.
b. Write a Program to implement Composite design pattern.
10 Case Study : Banking System

11 Describe the Methods to analyze the complexity of design patterns

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.

Preparing Software Requirements Specifications


Once all possible FRs and non-FRs have been identified, which are complete, consistent, and non-ambiguous, the
Software Requirements Specification (SRS) is to be prepared.
IEEE provides a template , also available here, which could be used for this purpose. The SRS is prepared by the
service provider, and verified by its client. This document serves as a legal agreement between the client and the
service provider. Once the concerned system has been developed and deployed, and a proposed feature was not
found to be present in the system, the client can point this out from the SRS. Also, if after delivery, the client says a
new feature is required, which was not mentioned in the SRS, the service provider can again point to the SRS. The
scope of the current experiment, however, doesn't cover writing a SRS.

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:

Project Estimation Techniques


● Estimation is the process of finding an estimate, or approximation, which is a value that can be used for some
purpose even if input data may be incomplete, uncertain, or unstable. Estimation determines how much
money, effort, resources, and time it will take to build a specific system or product.
Some important project parameters that are estimated include:
o Project size: What would be the size of the code written say, in number of lines, files, modules?
o Cost: How much would it cost to develop a software? A software may be just pieces of code, but one
has to pay to the managers, developers, and other project personnel.
o Duration: How long would it be before the software is delivered to the clients?
o Effort: How much effort from the team members would be required to create the software?

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

Semidetached: A development project can be categorized as semidetached type, if


● The team consists of some experienced as well as inexperienced staff
● Team members may have some experience on the type of system to be developed

Embedded: Embedded type of development project are those, which


● Aims to develop a software strongly related to machine hardware
● Team size is usually large
ACROPOLIS INSTITUTE OF TECHNOLOGY & RESEARCH, INDORE
Boehm suggested that estimation DEPARTMENT OFshould
of project parameters COMPUTER SCIENCE
be done through three stages: Basic COCOMO,
Intermediate COCOMO, and Complete COCOMO.

Basic COCOMO Model


The basic COCOMO model helps to obtain a rough estimate of the project parameters. It estimates effort and
time required for development in the following way:
Effort = a * (KDSI)b PM
Tdev = 2.5 * (Effort)c Months
Person Required = Efforts/Tdev Persons
where
● KDSI is the estimated size of the software expressed in Kilo Delivered Source Instructions
● a, b, c are constants determined by the category of software project
● Effort denotes the total effort required for the software development, expressed in person months
(PMs)
● Tdev denotes the estimated time required to develop the software (expressed in months)
The value of the constants a, b, c are given below:
Software project a b C
2 1. 0.
Organic
.4 05 38
3 1. 0.
Semi-detached
.0 12 35
3 1. 0.
Embedded
.6 20 32

Intermediate COCOMO Model


The basic COCOMO model considers that effort and development time depends only on the size of the
software. However, in real life there are many other project parameters that influence the development process.
The intermediate COCOMO take those other factors into consideration by defining a set of 15 cost drivers
(multipliers) as shown in the table below . Thus, any project that makes use of modern programming practices
would have lower estimates in terms of effort and cost. Each of the 15 such attributes can be rated on a six-point
scale ranging from "very low" to "extra high" in their relative order of importance. Each attribute has an effort
multiplier fixed as per the rating. The product of effort multipliers of all the 15 attributes gives the Effort
Adjustment Factor (EAF).

Cost drivers for Intermediate COCOMO

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

EAF is used to refine the estimates obtained by basic COCOMO as follows:

c
Effort|corrected = Effort * EAF Tdev|corrected = 2.5 * (Effort| corrected)

Complete COCOMO Model


Both the basic and intermediate COCOMO models consider a software to be a single homogeneous entity -- an
assumption, which is rarely true. In fact, many real life applications are made up of several smaller sub-systems.
(One might not even develop all the sub-systems -- just use the available services). The complete COCOMO model
takes these factors into account to provide a far more accurate estimate of project metrics.
To illustrate this, consider a very popular distributed application: the ticket booking system of the Indian
Railways. There are computerized ticket counters in most of the railway stations of our country. Tickets can be
booked / cancelled from any such counter. Reservations for future tickets, cancellation of reserved tickets could
also be performed. On a high level, the ticket booking system has three main components:
● Database
ACROPOLIS INSTITUTE OF TECHNOLOGY & RESEARCH, INDORE
● DEPARTMENT OF COMPUTER SCIENCE
Graphical User Interface (GUI)
● Networking facilities
Among these, development of the GUI is considered as an organic project type; the database module could be
considered as a semi-detached software. The networking module can be considered as an embedded software. To
obtain a realistic cost, one should estimate the costs for each component separately, and then add it up.
Advantages of COCOMO
COCOMO is a simple model, and should help one to understand the concept of project metrics estimation.
Drawbacks of COCOMO
COCOMO uses KDSI, which is not a proper measure of a program's size. Indeed, estimating the size of a
software is a difficult task, and any slight miscalculation could cause a large deviation in subsequent project
estimates. Moreover, COCOMO was proposed in 1981 keeping the waterfall model of project life cycle in
mind [2]. It fails to address other popular approaches like prototype, incremental, spiral, agile models. Moreover,
in present day a software project may not necessarily consist of coding of every bit of functionality. Rather,
existing software components are often used and glued together towards the development of a new software.
COCOMO is not suitable in such cases.
COCOMO II was proposed later in 2000 to many of address these issues.

Halstead's Complexity Metrics


Halstead took a linguistic approach to determine the complexity of a program. According to him, a computer
program consists of a collection of different operands and operators. The definition of operands and operators
could, however, vary from one person to another and one programming language to other. Operands are usually
the implementation variables or constants -- something upon which an operation could be performed. Operators
are those symbols that affects the value of operands. Halstead's metrics are computed based on the operators
and operands used in a computer program. Any given program has the following four parameters:
● n1: Number of unique operators used in the program
● n2: Number of unique operands used in the program
● N1: Total number of operators used in the program
● N2: Total number of operands used in the program
Using the above parameters one compute the following metrics:
● Program Length: N = N1 + N2
● Program Vocabulary: n = n1 + n2
● Volume: V = N * lg n
● Difficulty: D = (n1 * N2) / (2 * n2)
● Effort: E = D * V
● Time to Implement: T = E / 18 (in seconds)
The program volume V is the minimum number of bits needed to encode the program. It represents the size
of the program while taking into account the programming language.
The difficulty metric indicates how difficult a program is to write or understand.
Effort denotes the "mental effort" required to develop the software, or to recreate the same in another
programming language.
ACROPOLIS INSTITUTE OF TECHNOLOGY & RESEARCH, INDORE
DEPARTMENT OF COMPUTER
EXPERIMENT 3 SCIENCE

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:

Use case diagrams


Use case diagrams belong to the category of behavioral diagram of UML diagrams. Use case diagrams aim to
present a graphical overview of the functionality provided by the system. It consists of a set of actions (referred to
as use cases) that the concerned system can perform, one or more actors, and dependencies among them.

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.

Actors can be classified as below:

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.

A use case diagram for a book store

Association between Actors and Use Cases


A use case is triggered by an actor. Actors and use cases are connected through binary associations indicating
that the two communicates through message passing.

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.

Use Case Relationships


Three types of relationships exist among use cases:

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:

Determine the system boundary

Ensure that individual actors have well-defined purpose

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:

Entity Relationship Model


An entity relationship diagram (ERD) shows the relationships of entity sets stored in a database. An entity in this
context is an object, a component of data. An entity set is a collection of similar entities. These entities can have
attributes that define its properties.
By defining the entities, their attributes, and showing the relationships between them, an ER diagram illustrates the
logical structure of databases.
ER diagrams are used to sketch out the design of a database.
For example, student and school -- they are two entities. Students study in school. So, these two entities are
associated with a relationship "Studies in".

Entity Set and Relationship Set


An entity set is a collection of all similar entities. For example, "Student" is an entity set that abstracts all students.
Ram, John are specific entities belonging to this set. Similarly, a "Relationship" set is a set of similar relationships.

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.

Entity Generalization and Specialization


Once we have identified the entity sets, we might find some similarities among them. For example, multiple
person interacts with a banking system. Most of them are customers, and rest employees or other service
providers. Here, customers, employees are persons, but with certain specializations. Or in other way, person is
the generalized form of customer and employee entity sets.
ER model uses the "ISA" hierarchy to depict specialization (and thus, generalization).

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.

Graphical Notations for ER Diagram


Term Notation Remarks
Name of the set is
Entity set written inside the
rectangle
Name of the
Attribute attribute is written
inside the ellipse

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:

Structural and Behavioral aspects:

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:

It is a graphical representation for describing a system in context of its static construction.

Elements in 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.

Classification of Design Patterns

These patterns are also called as GOF patterns (Gang-Of-Four). Their names are listed in the
table given below.

o Creational patterns concern the process of object creation

o Structural patterns deal with the composition of classes and objects

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:

• Class patterns deal with relationships between classes and their


subclasses. These relationships are established through inheritance, so
they are static.

• Object patterns deal with object relationships, which can be changed at


run-time and are more dynamic.

The following table shows the classification of design patterns. Note, that those are the patterns
introduced by the Gang of Four.

Purpose Design Patterns Scope


Creational Abstract Factory
Object
Builder Object

Factory Method Class

Prototype Object
Singleton Object
Structural Adapter Class
ACROPOLIS INSTITUTE OF TECHNOLOGY & RESEARCH, INDORE
Bridge DEPARTMENT OF COMPUTERObject
SCIENCE
State Object

Strategy Object

Template Method Class

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 design patterns

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

Match interfaces of different classes

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 design patterns

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 class patterns use inheritance to distribute behaviour between classes.

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

Alter an object's behavior when its state changes

o Strategy
Encapsulates an algorithm inside a class

o Template method
Defer the exact steps of an algorithm to a subclass

o Visitor

Defines a new operation to a class without change

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.

Method Overriding Example

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

public void eat()

{
System.out.println("Human is eating");
}
}

class Boy extends Human{

//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.

o It is used to achieve abstraction.


o By interface, we can support the functionality of multiple inheritance.
o It can be used to achieve loose coupling.

Sample Code:

interface printable{

void print();

class A6 implements printable{

public void print(){System.out.println("Hello");}

public static void main(String args[]){

A6 obj = new A6();

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:

abstract class Bike{

abstract void run();

class Honda4 extends Bike{

void run(){System.out.println("running safely..");}

public static void main(String args[]){

Bike obj = new Honda4();

obj.run();

Output: running safely

Conclusion: Thus we have executed basic java programs successfully.

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.

Also Known As:

• Virtual Constructor .

Applicability:

Use the Factory Method pattern when

· a class can't anticipate the class of objects it must create.

· a class wants its subclasses to specify the objects it creates.

· 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

public class Rectangle implements Shape {

@Override
public void draw() {
System.out.println("Inside Rectangle::draw() method.");

}
}
Square.java

public class Square implements Shape {

@Override
public void draw() {
System.out.println("Inside Square::draw() method.");
}
}

Circle.java

public class Circle implements Shape {


ACROPOLIS INSTITUTE OF TECHNOLOGY & RESEARCH, INDORE

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

public class FactoryPatternDemo {

public static void main(String[] args) {


ShapeFactory shapeFactory = new ShapeFactory();

//get an object of Circle and call its draw method.


ACROPOLIS INSTITUTE OF TECHNOLOGY & RESEARCH, INDORE

shape1.draw();
DEPARTMENT OF COMPUTER SCIENCE

//get an object of Rectangle and call its draw method. Shape


shape2 = shapeFactory.getShape("RECTANGLE");

//call draw method of Rectangle


shape2.draw();
//get an object of Square and call its draw method.
Shape shape3 = shapeFactory.getShape("SQUARE");

//call draw method of circle


shape3.draw();
}

Step 5

Verify the output.

Inside Circle::draw() method. Inside


Rectangle::draw() method. Inside
Square::draw() method.
ACROPOLIS INSTITUTE OF TECHNOLOGY & RESEARCH, INDORE
DEPARTMENT OF COMPUTER SCIENCE
b. Aim: Write a program to implement abstract factory.

Theory:

• Create instances of classes belonging to different families.

• 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.

• In Abstract Factory pattern an interface is responsible for creating a factory of related


objects, without explicitly specifying their classes. Each generated factory can give the
objects as per the Factory pattern.

Intent:

Provide an interface for creating families of related or dependent objects without specifying
their concrete classes.

Also Known As: Kit

Applicability:

Use the Abstract Factory pattern when

· a system should be independent of how its products are created, composed, and represented.

· a system should be configured with one of multiple families of products.

· 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

public class Rectangle implements Shape {


ACROPOLIS INSTITUTE OF TECHNOLOGY & RESEARCH, INDORE
DEPARTMENT OF COMPUTER SCIENCE

@Override
public void draw() {
System.out.println("Inside Rectangle::draw() method.");
}
}
Square.java

public class Square implements Shape {

@Override
public void draw() {
System.out.println("Inside Square::draw() method.");
}
}

Circle.java

public class Circle implements Shape {

@Override
public void draw() {
System.out.println("Inside Circle::draw() method.");
}
}

Step 3
Create an interface for Colors.
Color.java

public interface Color {


void fill();
ACROPOLIS INSTITUTE OF TECHNOLOGY & RESEARCH, INDORE
DEPARTMENT OF COMPUTER SCIENCE

Step4
Create concrete classes implementing the same interface.
Red.java

public class Red implements Color {

@Override
public void fill() {
System.out.println("Inside Red::fill() method.");
}
}

Green.java

public class Green implements Color {


@Override
public void fill() {

System.out.println("Inside Green::fill() method.");


}
}

Blue.java

public class Blue implements Color {

@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

public abstract class AbstractFactory {


abstract Color getColor(String color);
abstract Shape getShape(String shape) ;
}

Step 6
Create Factory classes extending AbstractFactory to generate object of concrete class based on
given information.
ShapeFactory.java

public class ShapeFactory extends AbstractFactory {

@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 new Square();


}

return null;
}

@Override
Color getColor(String
color) { return null;
}

ColorFactory.java

public class ColorFactory extends AbstractFactory {

@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

public class FactoryProducer {


public static AbstractFactory getFactory(String choice){

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) {

//get shape factory


AbstractFactory shapeFactory = FactoryProducer.getFactory("SHAPE");

//get an object of Shape Circle


Shape shape1 = shapeFactory.getShape("CIRCLE");

//call draw method of Shape Circle


shape1.draw();

//get an object of Shape Rectangle


Shape shape2 = shapeFactory.getShape("RECTANGLE");

//call draw method of Shape Rectangle


shape2.draw();

//get an object of Shape Square


Shape shape3 = shapeFactory.getShape("SQUARE");
ACROPOLIS INSTITUTE OF TECHNOLOGY & RESEARCH, INDORE
DEPARTMENT OF COMPUTER SCIENCE

//call draw method of Shape Square


shape3.draw();

//get color factory


AbstractFactory colorFactory = FactoryProducer.getFactory("COLOR");

//get an object of Color Red


Color color1 = colorFactory.getColor("RED");

//call fill method of Red


color1.fill();

//get an object of Color Green


Color color2 = colorFactory.getColor("Green");

//call fill method of Green


color2.fill();
//get an object of Color Blue
Color color3 = colorFactory.getColor("BLUE");

//call fill method of Color Blue


color3.fill();
}
}

Step 9
Verify the output.

Inside Circle::draw() method.


Inside Rectangle::draw()
method. Inside Square::draw()
method.
Inside Red::fill()
method. Inside

Conclusion :

Thus we have executed programs for factory pattern and abstract factory successfully.
EXPERIMENT 9

a. Aim: Write a program to implement singleton pattern.

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.

• A class with only one single possible instance.

– Private constructor

– Global access

• Intent

Ensure a class has only one instance, and provide a global point of access to it.

Encapsulated "just-in-time initialization" or "initialization on first use".

Applicability:

• Use the Singleton pattern when

• 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

public class SingleObject {


//create an object of SingleObject
private static SingleObject instance = new SingleObject();
//make the constructor private so that this class cannot be
//instantiated
private SingleObject(){}
//Get the only object available
public static SingleObject
getInstance(){ return instance;
}
public void showMessage(){
System.out.println("Hello
World!");
}

Step 2
Get the only object from the singleton class.
SingletonPatternDemo.java

public class SingletonPatternDemo {


public static void main(String[] args) {

//illegal construct
//Compile Time Error: The constructor SingleObject() is not visible
//SingleObject object = new SingleObject();

//Get the only object available


SingleObject object = SingleObject.getInstance();

//show the message


object.showMessage();
}

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

Compose objects into tree structures to represent part-whole hierarchies.

• Applicability

Use the Composite pattern when

• you want to represent part-whole hierarchies of objects.

• 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 void add(Employee


e) { subordinates.add(e);
}

public void remove(Employee


e) { subordinates.remove(e);
}

public List<Employee>
getSubordinates(){ return
subordinates;
}

public String toString(){


return ("Employee :[ Name : " + name + ", dept : " + dept + ", salary :" + salary+" ]");
}

Step 2
Use the Employee class to create and print employee hierarchy.
CompositePatternDemo.java

public class CompositePatternDemo {


public static void main(String[] args) {

Employee CEO = new Employee("John","CEO", 30000);

Employee headSales = new Employee("Robert","Head Sales", 20000);

Employee headMarketing = new Employee("Michel","Head Marketing", 20000);

Employee clerk1 = new Employee("Laura","Marketing", 10000);


Employee clerk2 = new Employee("Bob","Marketing", 10000);

Employee salesExecutive1 = new Employee("Richard","Sales", 10000);


Employee salesExecutive2 = new Employee("Rob","Sales", 10000);

CEO.add(headSales);
CEO.add(headMarketin
g);

headSales.add(salesExecutive
1);
headSales.add(salesExecutive
2);

headMarketing.add(clerk1);
headMarketing.add(clerk2);

//print all employees of the


organization
System.out.println(CEO);

for (Employee headEmployee :


CEO.getSubordinates()) {
System.out.println(headEmployee);

for (Employee employee :


headEmployee.getSubordinates()) {
Step 3
Verify the output.

Employee :[ Name : John, dept : CEO, salary :30000 ]

Employee :[ Name : Robert, dept : Head Sales,

salary :20000 ]
Employee :[ Name : Richard, dept : Sales,

salary :10000 ] Employee :[ Name : Rob, dept : Sales,

salary :10000 ]

Employee :[ Name : Michel, dept : Head Marketing,

salary :20000 ] Employee :[ Name : Laura, dept : Marketing,

salary :10000 ]

Conclusion:

Thus, we have executed programs for singleton and composite pattern.


Aim : Case Study: Banking System

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.

Getting a Solution in Place:

Following an extensive search, the bank’s team identified Continuity Software’s


AvailabilityGuard as the preferred solution for protecting the bank against service availability
risks. The fact that AvailabilityGuard was already used by other large financial institutions gave
the team an added measure of confidence in the decision. To ensure the proper process was put
in place, the initial implementation was limited to 1,000 servers. A joint committee with
members from the Business Continuity and IT Operations groups was established. Over the first
six months of operating the system, the committee established and documented procedures for
problem identification, management reporting, and continuous improvement. The flexibility of
the AvailabilityGuard solution allowed the bank to seamlessly adapt the solution to support the
availability assurance processes established by the organization, including: Daily scan of the IT
infrastructure Automated routing of critical issues to the enterprise IT incident management
system, ensuring that risks are addressed immediately as they are uncovered Weekly, monthly,
and quarterly health and SLA compliance scores for each IT domain and business service
delivered to management as well as internal and external auditors One year following the initial
implementation, AvailabilityGuard is now used to monitor all Tier One and Tier Two business
services, encompassing over 6,000 servers.

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.

You might also like