Singleton Pattern

Implementation of the Singleton Pattern:

 

The singleton pattern can be implemented in a variety of ways. One common implementation involves the following steps:

 

Declare a private constructor: The constructor for the singleton class should be private. This will prevent other classes from directly creating instances of the singleton class.

 

Create a static field: A static field should be declared to hold the singleton instance. The field should be initialized to null before the first time it is accessed.

 

Create a synchronized getInstance() method: A synchronized method should be created to return the singleton instance. The method should first check if the static field is null. If it is, then the method should create a new instance of the singleton class and store it in the field.

 

Return the singleton instance: If the static field is not null, then the method should return the value of the field.

 

Example Code for the Singleton Pattern:

public class Car {
    
//    A static instance field is declared to hold the single instance of class.
//    The field is initially initialized to null to indicate that no instance exists.
    private static Car instance = null;

//    A private constructor, preventing direct instantiation of objects from outside the class.
//    This enforces the singleton pattern, ensuring that object creation is controlled within the class //  //   itself.
    private Car() {}

//    The getInstance() method acts as a factory method, returning the single instance. 
//    It utilizes synchronization to ensure thread-safe access to the instance field, 
//    preventing multiple threads from accessing or modifying it simultaneously.
    public static Car getInstance() {
        synchronized (Car.class) {
            if (instance == null) {
                instance = new Car();
            }
        }
        return instance;
    }
    
}

 

Now if we create difrent objects of Car class we recive the same instance of this calss

 

public class Main {
    public static void main(String[] args) {

        Car car = Car.getInstance();

        Car car2 = Car.getInstance();

        System.out.println(car == car2);

    }
}

 

The result of the comparison of the class is true

 

Leave a Comment

Your email address will not be published. Required fields are marked *