NotesWhat is notes.io?

Notes brand slogan

Notes - notes.io

Creational design pattern:

It is responsible for creation of objects.


1. Singleton:
-> It is used when we have to create only one instance of a class.
-> Can be done using:
Eager initialisation
Lazy initialisation
Synchronized Method
Double locking


- The Singleton pattern ensures that a class has only one instance throughout the entire application.
- It provides global access to this single instance from anywhere in the codebase.
- Essentially, it restricts the instantiation of a class to a single object.
- Common use cases include logging, caching, database connections, and thread pools.

Initialization Types of Singleton:
- Early Initialization:
- The class is initialized whether it is needed or not (at class loading).
- Simple but not efficient if the class is rarely used.
- Lazy Initialization:
- The class is initialized only when required (on-demand).
- Commonly used for creating singleton classes.

4. Key Components of Singleton Design Pattern:
- Static Member:
- A static member within the class ensures memory allocation only once, maintaining the single instance.
- Example: `private static Singleton instance;`
- Private Constructor:
- Make the default constructor private. This prevents external code from creating new instances using the new operator.
- Example: `private Singleton() { }`

5. Advantages of Singleton Design Pattern:
- Single Instance: Ensures only one instance exists.
- Global Access: Provides a consistent way to access that instance.
- Resource Efficiency: Avoids unnecessary object creation.

6. Disadvantages:
- Tight Coupling: Singleton can lead to tight coupling in the codebase.
- Testing Challenges: Testing singletons can be tricky due to their global nature.


public class DatabaseConnection {
private static DatabaseConnection instance; // Singleton instance

private DatabaseConnection() {
// Private constructor to prevent external instantiation
// Initialize database connection here
}

public static DatabaseConnection getInstance() {
if (instance == null) {
instance = new DatabaseConnection(); // Create the instance if not already done
}
return instance;
}

// Other methods for database operations...
}

// Usage:
DatabaseConnection dbConnection = DatabaseConnection.getInstance();
// Now use 'dbConnection' to interact with the database

In this example, the DatabaseConnection class acts as a Singleton. It doesn’t have a public constructor, so the only way to get its object is by calling getInstance(). This method caches the first created object and returns it in subsequent calls.











Double locking is a concept often used in multithreading to ensure that a resource (such as an object or a piece of data) is safely initialized and accessed by multiple threads. Let me break it down in simple terms:

1. Single Locking:
- Imagine you have a shared resource (like a global configuration object) that multiple threads need to access.
- Without any synchronization, all threads might try to initialize or modify the resource simultaneously.
- This can lead to race conditions, where one thread overwrites the changes made by another thread, causing unexpected behavior.
- To prevent this, you can use a lock (like a mutex or a semaphore) to ensure that only one thread can access the resource at a time.
- This is called single locking because you use a single lock to protect the resource.

2. Double Locking:
- Now, let's say you want to optimize the performance.
- In single locking, every time a thread accesses the resource, it acquires the lock, even if the resource is already initialized.
- Double locking comes into play here:
- When a thread first accesses the resource, it checks whether it's already initialized.
- If not, it acquires the lock and initializes the resource.
- But what if another thread arrives just after the first thread checks but before it acquires the lock?
- The second thread might see the resource as uninitialized and also try to initialize it.
- To prevent this, the first thread performs a second check (hence the name "double locking") inside the critical section (i.e., while holding the lock).
- If the resource is still uninitialized, it initializes it. Otherwise, it skips the initialization.
- This way, subsequent threads don't need to acquire the lock unnecessarily if the resource is already initialized.

3. Example with a Database Connection:
- Imagine a database connection pool that needs to be lazily initialized.
- Using double locking:
1. Thread A checks if the pool is initialized (first check).
2. If not, it acquires the lock, initializes the pool, and releases the lock.
3. Thread B arrives and checks if the pool is initialized (first check).
4. Since Thread A already initialized it, Thread B skips the lock acquisition and proceeds.
5. Thread A performs a second check (inside the critical section) to ensure no other thread initialized it in the meantime.
6. If everything is fine, both threads can now safely use the initialized pool.



public static ResourcePool getInstance() {
if (instance == null) { // First check
synchronized (ResourcePool.class) {
if (instance == null) { // Second check inside critical section
instance = new ResourcePool();
instance.initializePool(); // Initialize the pool
instance.initialized = true; // Mark as initialized
}
}
}
return instance;
}




















2. Prototype:
-> It is used when we have to make a copy or clone from Existing object and the obj creation is expensive or implemention is complex.

Creating a Spreadsheet Application
a spreadsheet application that allows users to create and manage spreadsheets with multiple cells. Each cell can have various attributes such as font style, background color, and alignment. Implementing this efficiently using the Prototype Design Pattern makes sense. Here's how it works:

1. Product (Cell) :
- We define a `Cell` class as our product. This class represents an individual cell in the spreadsheet.
- The `Cell` class contains attributes like font style, background color, and alignment.
- It implements the `Cloneable` interface to enable cloning.


class Cell implements Cloneable {
private String content;
private String fontStyle;
private String backgroundColor;
// Other attributes...

// Constructor and other methods...

@Override
public Cell clone() {
try {
return (Cell) super.clone();
} catch (CloneNotSupportedException e) {
// Handle cloning exception
return null;
}
}
}


2. Client Code (Spreadsheet):
- In your spreadsheet application, when a user creates a new cell, you don't want to create it from scratch.
- Instead, you create a prototype cell (template) with default attributes.
- When the user wants to add a new cell, you clone the prototype cell and customize it as needed.


public class Spreadsheet {
private Cell prototypeCell; // The prototype cell

public Spreadsheet() {
// Initialize the prototype cell with default attributes
prototypeCell = new Cell();
prototypeCell.setContent("");
prototypeCell.setFontStyle("Arial");
prototypeCell.setBackgroundColor("White");
// Set other default attributes...
}

public Cell createNewCell() {
// Clone the prototype cell and return a new cell
return prototypeCell.clone();
}
}


3. Usage:
- When a user wants to add a new cell to the spreadsheet, you call `createNewCell()`.
- The cloned cell inherits the default attributes from the prototype but can be customized further.

public static void main(String[] args) {
Spreadsheet spreadsheet = new Spreadsheet();

// Create a new cell (cloned from the prototype)
Cell cell1 = spreadsheet.createNewCell();
cell1.setContent("Hello, World!");
cell1.setFontStyle("Bold");

// Create another cell
Cell cell2 = spreadsheet.createNewCell();
cell2.setContent("12345");
cell2.setBackgroundColor("LightYellow");
}


Advantages of Using Prototype Design Pattern:

-Efficiency: Cloning existing cells is faster than creating new ones from scratch.
-Customization: Users can modify cloned cells without affecting the prototype.
-Dynamic Creation: New cell types can be added at runtime without changing client code.



3. Factory:
->

4. Abstract Factory:
->

5. Builder:
->
     
 
what is notes.io
 

Notes.io is a web-based application for taking notes. You can take your notes and share with others people. If you like taking long notes, notes.io is designed for you. To date, over 8,000,000,000 notes created and continuing...

With notes.io;

  • * You can take a note from anywhere and any device with internet connection.
  • * You can share the notes in social platforms (YouTube, Facebook, Twitter, instagram etc.).
  • * You can quickly share your contents without website, blog and e-mail.
  • * You don't need to create any Account to share a note. As you wish you can use quick, easy and best shortened notes with sms, websites, e-mail, or messaging services (WhatsApp, iMessage, Telegram, Signal).
  • * Notes.io has fabulous infrastructure design for a short link and allows you to share the note as an easy and understandable link.

Fast: Notes.io is built for speed and performance. You can take a notes quickly and browse your archive.

Easy: Notes.io doesn’t require installation. Just write and share note!

Short: Notes.io’s url just 8 character. You’ll get shorten link of your note when you want to share. (Ex: notes.io/q )

Free: Notes.io works for 12 years and has been free since the day it was started.


You immediately create your first note and start sharing with the ones you wish. If you want to contact us, you can use the following communication channels;


Email: [email protected]

Twitter: http://twitter.com/notesio

Instagram: http://instagram.com/notes.io

Facebook: http://facebook.com/notesio



Regards;
Notes.io Team

     
 
Shortened Note Link
 
 
Looding Image
 
     
 
Long File
 
 

For written notes was greater than 18KB Unable to shorten.

To be smaller than 18KB, please organize your notes, or sign in.