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

Data structure: Doubly Linked List
admin07/04/2024

Data structure: Doubly Linked List
In this article, I would like to show you about Data structure - Doubly Linked List
TypeScript Design Pattern - Builder
admin07/08/2023

TypeScript Design Pattern - Builder
TypeScript Design Pattern - Builder
Create Cognito User Pool with AWS CDK
admin09/06/2023

Create Cognito User Pool with AWS CDK
In the previous post, I showed you how to create a simple S3 bucket. Next, in this article, I will guide you to create a Cognito User Pool.
Newest

How to create scroll animations with Next.js App
admin08/04/2024

How to create scroll animations with Next.js App
A Beginner's Guide to Using AOS Library with Next.js application
TypeScript Design Pattern - Adapter
admin08/08/2023

TypeScript Design Pattern - Adapter
This design pattern acts as a bridge between two different interfaces.
What are data structures?
admin06/04/2024

What are data structures?
In this article, I would like to introduce the Data Structures for a beginner's guide
Đ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