DEV Community

Farhan Roy -- | šŸ˜
Farhan Roy -- | šŸ˜

Posted on

Design pattern: Singelton

There are so many types of design patterns to make it easier to solve problems in the program. But this time I only discuss the Singelton, so what is the singleton?
image

Apa itu Singelton Patttern ?

The Singleton Pattern is a pattern whose goal is that a class can only be instanced once. Unlike regular classes that don't use Singelton, which can create multiple instances.

Why use singleton , why not just use a normal class ?

Example program

public class Singleton
{
  private static Singleton instance;

  private Singleton(){}

  public static Singleton GetInstance()
  {
    if(instance==null)
      instance=new Singleton();

    return instance;
  }
}
Enter fullscreen mode Exit fullscreen mode

Pros

  1. You can be sure that a class has only a single instance.
  2. You gain a global access point to that instance.
  3. The singleton object is initialized only when itā€™s requested for the first time.

Cons

  1. Violates the Single Responsibility Principle. The pattern solves two problems at the time.
  2. The Singleton pattern can mask bad design, for instance, when the components of the program know too much about each other.
  3. The pattern requires special treatment in a multi-threaded environment so that multiple threads wonā€™t create a singleton object several times. (using Multi-Thread ā€” Lazy Load Singleton)

Top comments (0)