Danh mụcThẻBài viết

admin

I'm a Full-stack developer

Thẻ

Linked List
Data Structure
Chat GPT
Design Pattern
Microservices
API
AWS CDK
ReactJS
AWS Lightsail
Flutter Mobile
TypeScript Design Pattern - Singleton
Ngày đăng: 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

Đề xuất

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.
TypeScript Design Pattern - Proxy
admin11/08/2023

TypeScript Design Pattern - Proxy
Provide a surrogate or placeholder for another object to control access to it.
TypeScript Design Pattern - Builder
admin07/08/2023

TypeScript Design Pattern - Builder
TypeScript Design Pattern - Builder
Mới nhất

Create S3 Bucket with AWS CDK
admin09/06/2023

Create S3 Bucket with AWS CDK
In this article, I introduce Amazon CDK and how to write AWS infrastructure-as-code using TypeScript. We will do it step by step.
TypeScript Design Pattern - Adapter
admin08/08/2023

TypeScript Design Pattern - Adapter
This design pattern acts as a bridge between two different interfaces.
Đ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.
Đ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
Góp ý
Họ & Tên
Số điện thoại
Email
Nội dung
Tải ứng dụng
hotline

copyright © 2023 - AGAPIFA

Privacy
Term
About