Download as pdf or txt
Download as pdf or txt
You are on page 1of 11

ID: 2200032076_Sk JALEEL BASHA_AOOP

Lab experiment-1
1. Describe about Creational Pattern and its benefits?

Creational patterns are a type of design pattern that deal with the creation of objects. They are used to
abstract the process of object creation and to provide a more flexible and reusable way to create
objects.

1. Abstraction: Creational patterns abstract the process of object creation, which makes the code
more reusable and flexible.
2. Encapsulation: Creational patterns encapsulate the creation of objects, which makes the code
more maintainable and testable.
3. Code reuse: Creational patterns can be used to reuse code for creating different types of
objects.
4. Increased flexibility: Creational patterns can be used to increase the flexibility of a system by
allowing the objects to be created in different ways.

2. Draw the UML Relationship Diagram for Singleton Pattern for any customized scenario.

A)
ID: 2200032076_Sk JALEEL BASHA_AOOP

In-Lab:

A. Write a Java Program on Singleton Pattern for Real-life Logging System Scenario One
common use case for the Singleton pattern is in implementing logging systems, where
it’s important to ensure that only one instance of the logger is used throughout the
entire application. Note: The Logger class uses the Singleton pattern to ensure that only
one instance of the logger is created and used throughout the entire application. The
Instance property provides a way to access the single instance of the logger, and the
Log method can be used to log messages.

• Procedure/Program:

class Logger {

private static Logger _instance = null;

private Logger() {

public static Logger getInstance() {

if (_instance == null) {

_instance = new Logger();

return _instance;

public void log(String message) {

System.out.println(message);

public class Main {

public static void main(String[] args) {


ID: 2200032076_Sk JALEEL BASHA_AOOP

Logger logger = Logger.getInstance();

logger.log("This is a log message.");

Data and Results:

Data

• The logger class has two private variables: _instance and message.
• The _instance variable is a reference to the single instance of the Logger class.
• The message variable is a string that contains the log message.

Results

• The getInstance() method returns the single instance of the Logger class.
• The log() method prints the log message to the console.

Conclusion

The Java program for the Singleton pattern for a real-life logging system scenario
successfully creates a Logger class that uses the Singleton pattern to ensure that only
one instance of the logger is created and used throughout the entire application. The
getInstance() method provides a way to access the single instance of the logger, and the
log() method can be used to log messages.

Analysis and Inferences:

• The Singleton pattern is a design pattern that ensures that only one instance of
a class is created. This is useful in cases where it is important to have a single
point of access to an object, such as in a logging system.
• The getInstance() method is a static method that returns the single instance of
the Logger class. This method is used to get a reference to the logger object.
• The log() method is a method that logs a message to the console. This method
takes a string as a parameter, which is the message that will be logged.
ID: 2200032076_Sk JALEEL BASHA_AOOP

• The main() method of the Main class creates a Logger object and calls
the log() method to log a message. The log() method prints the message to the
console.

The Singleton pattern is a powerful tool that can be used to ensure that only one
instance of a class is created. This can be useful in a variety of situations, such as in
logging systems, database connections, and thread pools.

Here are some inferences that can be made from the Java program:

• The Singleton pattern can be implemented in Java using a private constructor and
a static method that returns the single instance of the class.
• The Singleton pattern can be used to ensure that only one instance of a class is
created, even if multiple objects of the class are requested.
• The Singleton pattern can be used to simplify the code and make it more
maintainable.

Sample VIVA-VOCE Questions (In-Lab):

1. Which classes are candidates of Singleton? Which kind of class do you make
Singleton in Java?
Classes that are candidates for the Singleton pattern are classes that need to have
only one instance in the entire application. This could be because the class
represents a shared resource, such as a database connection or a logger, or
because the class needs to be thread-safe.
2.State about Lazy Initialization.
Lazy initialization is a design pattern that delays the creation of an object until it is
actually needed. This can be useful in cases where the object is expensive to create or
where the object is only needed occasionally.

In Java, lazy initialization can be implemented by using a private static field and a static
method that returns the instance of the object. The private static field is initialized to
null when the class is loaded, and the static method checks to see if the field is null
before creating the object. If the field is null, the object is created and the field is set to
the reference to the object.

3. State about Eager Initialization.


ID: 2200032076_Sk JALEEL BASHA_AOOP

Eager initialization is a design pattern that creates an object as soon as the class is
loaded into memory. This means that there is always one instance of the class, even if
the class is never used.

In Java, eager initialization can be implemented by using a private static field and a static
initializer block. The private static field is initialized to the object in the static initializer
block. The static initializer block is executed when the class is loaded into memory, so
the object is created as soon as the class is loaded.

4. Discuss about “Why Singleton is Anti pattern?”

the Singleton pattern is considered an anti-pattern

• It can lead to tight coupling. The Singleton pattern tightly couples the code that
uses the Singleton object to the Singleton class itself. This can make it difficult to
test the code and to change the Singleton class without affecting the code that
uses it.
• It can make it difficult to mock or stub the Singleton object. In unit testing, it is
often necessary to mock or stub objects in order to test the code that uses them.
However, the Singleton pattern makes it difficult to mock or stub the Singleton
object, as the object is always created in the same way.
• It can lead to global state. The Singleton pattern creates a global state, as there is
only one instance of the Singleton object. This can make it difficult to reason
about the behavior of the system, as the state of the Singleton object can affect
the behavior of other parts of the system.

In general, the Singleton pattern should be avoided unless it is absolutely necessary.


There are other ways to ensure that there is only one instance of a class, such as using
the Factory pattern or the Dependency Injection pattern.

5. List the comparison between “Singleton vs Static Class”

• Singleton:

I. The Singleton pattern can be more efficient than a static class if the
instance is only needed occasionally.
II. The Singleton pattern can be more thread-safe than a static class if the
instance is created in a thread-safe manner.
III. The Singleton pattern can be more difficult to test than a static class.
ID: 2200032076_Sk JALEEL BASHA_AOOP

• Static Class:

I. The static class can be more flexible than a Singleton class, as the instance
can be created and destroyed at any time.
II. The static class can be more easily tested than a Singleton class.
Post-Lab:
A. In a Banking process, create a Singleton pattern to manage the Login
state of the user in all the operations like View Balance, Deposit &
Withdraw.
Note: Create a Singleton Class to maintain the User Login-State.
• Procedure/Program:

public class UserLoginState


{
private static UserLoginState instance;
private boolean isLoggedIn;
private UserLoginState()
{
isLoggedIn = false;
}
public static UserLoginState getInstance()
{
if (instance == null)
{
instance = new UserLoginState();
}
return instance;
}
ID: 2200032076_Sk JALEEL BASHA_AOOP

public boolean isLoggedIn()


{
return isLoggedIn;
}

public void login()


{
isLoggedIn = true;
System.out.println("User logged in successfully!");
}

public void logout() {


isLoggedIn = false;
System.out.println("User logged out successfully!");
}
ID: 2200032076_Sk JALEEL BASHA_AOOP

public class BankingProcess {


public static void main(String[] args) {
UserLoginState loginState = UserLoginState.getInstance

loginState.login();

if (loginState.isLoggedIn()) {
viewBalance();

deposit(1000);

// Withdraw
withdraw(500);
}

// Simulate user logout


loginState.logout();
}

public static void viewBalance() {


// Code to view user's balance
System.out.println("Viewing balance: $2000");
}

public static void deposit(int amount) {


// Code to deposit the specified amount
System.out.println("Depositing: $" + amount);
}
ID: 2200032076_Sk JALEEL BASHA_AOOP

public static void withdraw(int amount) {


// Code to withdraw the specified amount
System.out.println("Withdrawing: $" + amount);
}
}


Data and Results:
User logged in successfully!
Viewing balance: $2000
Depositing: $1000
Withdrawing: $500
User logged out successfully!

• Analysis and Inferences:

Analysis:

1. Singleton Pattern Implementation: The Singleton pattern ensures that only one
instance of the UserLoginState class is created and provides a global point of
access to that instance. The implementation follows the classic lazy initialization
method to create the instance only when needed.
2. Purpose of Singleton: The purpose of implementing the Singleton pattern in this
banking process is to maintain a single global state for user login throughout the
application. This ensures that different parts of the application can access and
modify the same login state, preventing multiple instances of the UserLoginState
class from being created.
3. Handling User Login State: The UserLoginState class has a private boolean
variable isLoggedIn to store the state of the user login. It also provides methods
to simulate user login and logout (login() and logout()). The state of the user login
is used to control the execution of banking operations, such as view balance,
deposit, and withdraw.

Inferences
• The Singleton pattern effectively ensures that there is only one instance of the U
The Singleton pattern effectively ensures that there is only one instance of the
UserLoginState class throughout the application, which helps maintain a consistent user
ID: 2200032076_Sk JALEEL BASHA_AOOP

login state.

• The provided code demonstrates a basic flow for handling user login, executing
banking operations, and logging out the user.
• However, the code is a simplified example and should not be used in a real
banking application without proper security measures, data persistence, and user
authentication.
• For a complete and secure banking application, additional layers of security, data
storage, and user authentication would be essential.
ID: 2200032076_Sk JALEEL BASHA_AOOP

You might also like