0% found this document useful (0 votes)
21 views

Lecture 6 - Creational Pattern Singlenton Pattern

Uploaded by

tajrianaltahrim
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views

Lecture 6 - Creational Pattern Singlenton Pattern

Uploaded by

tajrianaltahrim
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 26

Lecture 6

Kazi Rifat Ahmed


Lecturer
Department of Software Engineering
Daffodil International University
Creational Pattern
● What is creational Pattern
● Types of creational pattern
● Where creational pattern can be
used
● What is singleton pattern and its

Outline principle
● Single object
● Where it is necessary
● Where it can be implemented
● Real life problem and its
necessary
Creational Pattern
What is Creational Patterns?
➔ In software engineering, creational design patterns are reusable
templates that provide solutions to common object creation
problems.
➔ They help to create objects in a flexible and efficient way, while
promoting loose coupling and code reusability.
➔ By using creational patterns, you can improve the design of your
software and make it easier to maintain and extend.
Benefits of Creational Patterns
They provide a number of benefits, including:
● Increased flexibility: Creational patterns allow you to create objects in a
variety of ways, which can make your code more adaptable to different
situations.
● Improved code reusability: Creational patterns can help you to reuse
code that creates objects, which can save you time and effort.
● Reduced complexity: Creational patterns can help to make your code
easier to understand and maintain, by encapsulating the object creation
process.
Types of Creational Patterns
Types of Creational Patterns
● Factory Method: Creates an object without specifying its exact class.
● Singleton: Ensures a class has only one instance and provides a global point
of access to it.
● Builder: Helps construct complex objects step-by-step.
● Prototype: Creates new objects by cloning existing ones.
● Abstract Factory: Creates families of related objects without specifying their
concrete classes.
● Object Pool: Provides a collection of pre-created objects that can be reused to
improve performance.
When to Use Creational Patterns
● When you need to create objects in a flexible way.
● When you want to hide the implementation details of object
creation from the rest of your code.
● When you want to promote loose coupling between different parts
of your code, which can make your code easier to understand and
change.
● When you want to improve the performance of your software by
reusing objects.
● When you want to make your code easier to maintain and extend.
Singelton Pattern
What is Singleton Patterns
❏ In software development, the Singleton pattern is a creational design
pattern that guarantees that a class has exactly one instance, and
provides a global access point to it.
❏ It's a commonly used approach for resource management,
configuration settings, and logging systems.
❏ By enforcing a single instance, the pattern helps maintain consistency,
avoid redundancy, and simplify access to shared resources.
❏ However, it's crucial to use the pattern judiciously, as overuse can lead
to tight coupling and testing challenges.
Principles of Singleton Patterns
● Restrict instantiation: The class's constructor is declared private,
preventing direct object creation.
● Provide global access: A static method provides a central access
point to the single instance.
● Single instance guarantee: This static method either returns the
existing instance (if it already exists) or creates a new one and
returns it.
Single Object COncept
➢ The Singleton pattern guarantees only one instance of a class
across the entire application.
➢ This instance plays a central role, often managing shared resources
or providing global functionality.
Benefits of Single Object Concepts
Benefits of this concept:

1. Consistency: All parts of the application work with the same data
and state.
2. Resource management: Centralized control over resources
prevents redundancy and potential conflicts.
3. Configuration: Simplifies global configuration management by
having a single point of reference.
Where Singleton Pattern Applicable
● Logging: Create a single logger instance to record system events
and maintain a centralized log file.
● Configuration: Implement a singleton to store and manage global
configuration settings, accessible from anywhere in the application.
● Database connection: Control access to a shared database
connection, preventing redundant connections and potential
resource exhaustion.
● Cache: Manage a centralized cache to improve performance by
storing frequently accessed data.
Real Life Problems and It’s Solution
Problem: Imagine a website that receives frequent requests from users.
If each request creates a new logger instance, disk usage and
performance could suffer.

Solution: The Singleton Pattern can ensure a single logger instance,


efficiently handling all logging needs.
Real Life Problems and It’s Solution
Problem: Multiple instances of a logger could lead to inconsistent
logging, performance issues, and difficulty in managing logs.

Solution: The singleton pattern ensures a single logger instance,


centralizing logging and simplifying management.

Benefits: Consistency, efficiency, ease of use, and centralized


configuration.
Real Life Problems and It’s Solution
Singleton Pattern Example
Step 1: Private Constructor
The first step in creating a Singleton is to make the constructor of the
class private. This prevents other classes from directly creating
instances of the Singleton class.

public class Singleton {


private static Singleton instance;

// Private constructor
private Singleton() {
// Initialization code, if needed
}
}
Singleton Pattern Example
Step 2: Static Instance

Next, we create a static method that provides access to the single instance
of the class. If an instance doesn’t exist, it creates one; otherwise, it
returns the existing instance.
public class Singleton {
private static Singleton instance;

private Singleton() {
// Initialization code, if needed
}

// Static method to get the instance


public static Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
Singleton Pattern Example
Step 3: Using the Singleton

Now, you can use the Singleton throughout your application:


public class Main {
public static void main(String[] args) {
// Get the Singleton instance
Singleton singleton = Singleton.getInstance();

// Use the Singleton


// ...
}
}
Singleton Pattern Example
Building a Thread-Safe Singleton in Java

Let’s dive into a Java code example to create a thread-safe Singleton:


Step 1: Private Constructor
The first step is to make the constructor of the class private. This prevents other
classes from directly creating instances of the Singleton class.

public class Singleton {


private static Singleton instance;

// Private constructor
private Singleton() {
// Initialization code, if needed
}
}
Singleton Pattern Example
Step 2: Static Instance with Double-Checked Locking
We create a static method that provides access to the single instance of the class. We
use double-checked locking to ensure thread safety. This technique minimizes
synchronization overhead by checking if the instance is null before entering a
synchronized block.
public class Singleton {
private static volatile Singleton instance;
private Singleton() {
// Initialization code, if needed
}
// Static method to get the instance
public static Singleton getInstance() {
if (instance == null) {
synchronized (Singleton.class) {
if (instance == null) {
instance = new Singleton();
}
}
}
return instance;
Singleton Pattern Example
Step 3: Using the Singleton

Now, you can use the Singleton throughout your application:


public class Main {
public static void main(String[] args) {
// Get the Singleton instance
Singleton singleton = Singleton.getInstance();

// Use the Singleton


// ...
}
}
References
1. https://medium.com/@thecodebean/singleton-design-pattern-implementation-in
-java-1fba4ecc959f
2. https://www.javatpoint.com/singleton-design-pattern-in-java
Thank You

You might also like