DEV Community

Farhan Roy -- | ๐Ÿ˜
Farhan Roy -- | ๐Ÿ˜

Posted on

1

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)

Image of Datadog

Create and maintain end-to-end frontend tests

Learn best practices on creating frontend tests, testing on-premise apps, integrating tests into your CI/CD pipeline, and using Datadogโ€™s testing tunnel.

Download The Guide

Top comments (0)

AWS Security LIVE!

Tune in for AWS Security LIVE!

Join AWS Security LIVE! for expert insights and actionable tips to protect your organization and keep security teams prepared.

Learn More

๐Ÿ‘‹ Kindness is contagious

Please leave a โค๏ธ or a friendly comment on this post if you found it helpful!

Okay