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

RESTful API - How to design?
admin09/06/2023

RESTful API - How to design?
In this article, I will describe the useful points of designing a good API.
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 - 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.
Mới nhất

TypeScript Design Pattern - Prototype
admin07/08/2023

TypeScript Design Pattern - Prototype
The prototype pattern is one of the Creational pattern groups. The responsibility is to create a new object through clone the existing object instead of using the new key. The new object is the same as the original object, and we can change its property does not impact the original object.
Part 5: Creating a Tag List Page on Ghost CMS
admin17/06/2023

Part 5: Creating a Tag List Page on Ghost CMS
In this article, I will show you how to create a Tag list page using the Casper theme.
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.
Đ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