DEV Community

Nhan Nguyen
Nhan Nguyen

Posted on

8

JavaScript Design Patterns - Creational - Singleton

Image description

Singleton pattern limits the number of instances of a particular object to just one while providing a global access point to this instance.

Singletons reduce the need for global variables, which avoids the risk of name collisions.

In the example below, we check in the constructor() { ... } if an Animal instance exists or if we need to create a new one.

class Animal {
  name;

  constructor() {
    if (typeof Animal.instance === 'object') {
      return Animal.instance;
    }

    Animal.instance = this;

    return this;
  }
}

export default Animal;
Enter fullscreen mode Exit fullscreen mode

You can see that code in action on Stackblitz here: https://stackblitz.com/edit/vitejs-vite-an7es6?file=main.js


I hope you found it useful. Thanks for reading. ๐Ÿ™

Let's get connected! You can find me on:

Image of Timescale

๐Ÿš€ pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applicationsโ€”without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read more โ†’

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more