пятница, 5 апреля 2024 г.

Singleton Design Pattern

    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 ways to create an object.

This pattern involves a single class which is responsible to create an object while making sure that only single object gets 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.

To implement a singleton pattern, we have different approaches, but all of them have the following common concepts.

  • Private constructor to restrict instantiation of the class from other classes.
  • Private static variable of the same class that is the only instance of the class.
  • Public static method that returns the instance of the class, this is the global access point for the outer world to get the instance of the singleton class.
    Lazy initialization method to implement the singleton pattern creates the instance in the global access method.
//Lazy initialization singleton
package com.journaldev.singleton;

public class LazyInitializedSingleton {

    private static LazyInitializedSingleton instance;

    private LazyInitializedSingleton(){}

    public static LazyInitializedSingleton getInstance() {
        if (instance == null) {
            instance = new LazyInitializedSingleton();
        }
        return instance;
    }
}

public class Main {
    public static void main(String[] args) {
        LazyInitializedSingleton singleton =
LazyInitializedSingleton .getInstance();
    }
}

    Thread-safe singleton class is to make the global access method synchronized so that only one thread can execute this method at a time.
//Thread-safe singleton
package com.journaldev.singleton;

public class ThreadSafeSingleton {

    private static ThreadSafeSingleton instance;

    private ThreadSafeSingleton(){}

    public static synchronized ThreadSafeSingleton getInstance() {
        if (instance == null) {
            instance = new ThreadSafeSingleton();
        }
        return instance;
    }

}

public class Main {
    public static void main(String[] args) {
        ThreadSafeSingleton singleton =
ThreadSafeSingleton .getInstance();
    }
}


Комментариев нет:

Отправить комментарий