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

What are the SOLID principles?
admin17/06/2023

What are the SOLID principles?
If we want to have good software, the infrastructure should be good first. We should learn more techniques that help to have better quality.
Semantic Versioning NodeJS
admin07/07/2023

Semantic Versioning NodeJS
How to Use Semantic Versioning in NPM
Đ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.
Mới nhất

Form validator in Flutter with EzValidator
admin04/01/2024

Form validator in Flutter with EzValidator
When I am working on Flutter with form. For ensuring data integrity, and handling user input errors. I want to show an error message below each TextField, Dropdown, Switch, ... if the user does not input or wrong input. The EzValidator help me to resolve this.
Design Patterns
admin07/08/2023

Design Patterns
The design pattern does not be a specific programming language. Almost programming languages might apply design patterns that to resolve a problem repeat.
Đ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