Skip to main content

Singleton Pattern

Singleton is a creational design pattern that lets you ensure that a class has only one instance, while providing a global access point to this instance. ~ Refactoring Guru

Singleton UML Class Diagram

The Singleton design pattern ensures a class has only one instance and provides a global access point to that instance. It is useful for controlling access to shared resources and simplifying code. However, it can mask bad design and requires special treatment in multithreaded environments.

Slides

Singleton Pattern
full screen click here

Step by Step Implementation

In this tutorial, we’ll build a Singleton Pattern in JavaScript to fetch data from a real API (https://courses.ianapplebaum.com/api). The Singleton Pattern ensures only one instance of ApiService is created, centralizing access to authenticated API calls.

API Key: gYsK1cbEr2xpdLPOIx8q8IuuMzgEITDPTFpWaSn4

Live Editor
function SingletonDemo() {
    class ApiService {
        // Private static field for storing the singleton instance
        static #instance;

        async fetchUser() {
        return "Fetching user data...";
    }
}

const [data, setData] = useState(null);

// Simulate fetching data
useEffect(() => {
    const apiService = new ApiService();
    apiService.fetchUser().then(result => setData(result));
}, []);

return <div>{data}</div>;
}

Result
Loading...