CategoryTagArticle

admin

I'm a Full-stack developer

Tag

Linked List
Data Structure
Chat GPT
Design Pattern
Microservices
API
AWS CDK
ReactJS
AWS Lightsail
Flutter Mobile
TypeScript Design Pattern - Singleton
Published date: 07/08/2023

What is a singleton pattern?


The singleton pattern is one of five design patterns in the Creational Design Pattern group. The singleton ensures only a single install is created in a class and provides a method to access this instance everywhere in a codebase.



When should I use the singleton pattern?


The singleton pattern should be used when a developer wants to:


  • Only one instance of a class throughout the entire application.
  • Shared resource, Logger, Configuration, Caching,...
  • Relation with other patterns: Abstract Factory, Builder, Prototype, Facade, ...


How to implement


For example, We will define a class that has a responsibility to get a database connection only.


export class DatabaseConnection {
  private static isConnected: boolean = false;
  private static db: Promise<DataSource>;

  public static getConnection(): Promise<DataSource> {
    if (this.isConnected) {
      return Promise.resolve(this.db);
    }

    this.db = this.connect();

    return Promise.resolve(this.db);
  }

  private static connect(): Promise<DataSource> {
    try {
      const con = new DataSource({});

      return con
        .initialize()
        .then(() => {
          this.isConnected = true;
          console.log('DB connection is OK');


          return Promise.resolve(con);
        })
        .catch((error) => {
          console.log('DB connection is BAD');

          return Promise.reject(error);
        });
    } catch (error) {
      return Promise.reject(error);
    }
  }
}


MySQLConnection.getConnection()
  .then(() => {
    server = app.listen(config.port, () => {
      logger.info(`Listening to port ${config.port as number}`);
    });
  })
  .catch(() => logger.error('Server error!'));


Pros and Cons

Pros:


  • Ensure a class only have a single instance.
  • Access to an instance everywhere.
  • Initialized only when it's requested for the first time.


Cons:


  • Violates the Single Responsibility Principle. The pattern solves two problems at the time.
  • The Singleton pattern can mask bad design, for instance, when the components of the program know too much about each other.
  • The pattern requires special treatment in a multithreaded environment so that multiple threads won’t create a singleton object several times.
  • It may be difficult to unit test the client code of the Singleton because many test frameworks rely on inheritance when producing mock objects. Since the constructor of the singleton class is private and overriding static methods is impossible in most languages, you will need to think of a creative way to mock the singleton. Or just don’t write the tests. Or don’t use the Singleton pattern.


Wrapping Up


Thank you for reading, and happy coding!

I hope this article will help make the concepts of the Singleton Pattern

Recommend

TypeScript Design Pattern - Singleton
admin07/08/2023

TypeScript Design Pattern - Singleton
The singleton ensures only a single install is created in a class and provides a method to access this instance everywhere in a codebase.
Part 2: Setup Custom Domain Zone + SSL for Ghost on AWS Lightsail
admin17/06/2023

Part 2: Setup Custom Domain Zone + SSL for Ghost on AWS Lightsail
In this section, I will continue to show you how to point Ghost Instance Static IP to your domain.
State management with redux in Flutter
admin14/06/2023

State management with redux in Flutter
In this article I will show an example to manage state in Flutter application using Redux.
Newest

ĐINH THÀNH CÔNG - Software Developer
admin12/01/2024

ĐINH THÀNH CÔNG - Software Developer
Cong Dinh - Software Developer - My personal website, where I write blogs on a variety of topics and where I have some experiments with new technologies.
TypeScript Design Pattern - Proxy
admin11/08/2023

TypeScript Design Pattern - Proxy
Provide a surrogate or placeholder for another object to control access to it.
How to secure your API gateway
admin17/04/2024

How to secure your API gateway
In this blog, I will cover the 6 methods that technology leaders need to incorporate to secure and protect APIs.
Đinh Thành Công Blog

My website, where I write blogs on a variety of topics and where I have some experiments with new technologies.

hotlinelinkedinskypezalofacebook
DMCA.com Protection Status
Feedback
Name
Phone number
Email
Content
Download app
hotline

copyright © 2023 - AGAPIFA

Privacy
Term
About