DEV Community

Cover image for Singleton Pattern
Sukma Rizki
Sukma Rizki

Posted on

Singleton Pattern

1.Purpose
The Singleton Pattern is a creational design pattern that ensures a class has only one instance and provides a global point of acces to that instance.it's commonly used managing shared resources like configuration settings, logging, or network connections.

  1. Core Concepts
  • Single Instance: The class ensures that only one instance of itself is created.
  • Global Access: Provides a global access point to this instance, allowing it to be accessed from anywhere in the application.
  1. Benefits
  • Controlled Access : Ensures tha a class has only one instance, controlling acces to shared resources.
  • Memory Efficiency: Reduces memory consumption by reusing the same instance.
  • Global State : Maintains a global state that can be accessed from anywhere. Let'go to Example Code.

Define the Singleton Class

Image description

Use The Singleton in App

Image description

However, it’s important to use Singleton Pattern judiciously as overuse can lead to issues with testing and can cause hidden dependencies.

You may provide additional references to make this writing more perfect.
Enjoy the Coding. Enjoy the Process

Top comments (0)