Patrones de dise帽o en Node.js

1

Qu茅 es Node.js y c贸mo impulsa tu negocio

2

Patrones de dise帽o esenciales en Node.js

3

Patr贸n Singleton y Factory en JavaScript

4

Implementaci贸n pr谩ctica de Singleton y Factory en JavaScript

5

Implementaci贸n del patr贸n Observer con EventEmitter en Node.js

6

Implementaci贸n de Middlewares en Node.js sin Express

7

Decorators e inyecci贸n de dependencias en JavaScript

Flujo de Datos con Node.js

8

Aprende qu茅 son Buffer y Streams en Node.js

9

C贸mo utilizar streams y pipelines en Node.js

10

C贸mo funciona el Event Loop en Node.js

11

Qu茅 es Libuv y c贸mo maneja la asincron铆a en Node.js

12

Estrategias para ejecutar c贸digo as铆ncrono en Node.js

Debugging y Diagn贸stico en Node.js

13

C贸mo utilizar el Debugger en Node.js para solucionar problemas

14

Uso de Diagnostic Channels en Node.js para observabilidad y diagn贸stico

15

Instrumentaci贸n y m茅tricas clave en performance para aplicaciones Node.js

16

Control de errores globales y manejo de se帽ales en Node.js

17

Implementaci贸n Eficiente de Logs con Pino en Node.js

Performance en Node.js

18

An谩lisis del event loop en aplicaciones Node.js usando Nsolid

19

C贸mo Diagnosticar y Solucionar Memory Leaks en Aplicaciones Node.js

20

Optimizar rendimiento en Node.js con Worker Threads y Child Processes

21

Optimiza y Escala Aplicaciones Node.js con T茅cnicas de Caching

Creando CLIs con Node.js

22

C贸mo crear aplicaciones CLI con Node.js

23

C贸mo Crear un CLI con Minimist y Manejar Argumentos en Node.js

24

Creaci贸n de un CLI con Node.js y Google Generative AI

25

Creaci贸n de Chat con IA usando CLI en Node

26

C贸mo Crear e Instalar tu Propio CLI de Node con npm

You don't have access to this class

Keep learning! Join and start boosting your career

Aprovecha el precio especial y haz tu profesi贸n a prueba de IA

Antes: $249

Currency
$209
Suscr铆bete

Termina en:

0 D铆as
14 Hrs
53 Min
40 Seg

Patr贸n Singleton y Factory en JavaScript

3/26
Resources

The Singleton pattern is one of the fundamental concepts in JavaScript that allows maintaining only one instance of an object during the entire execution of an application. Its use ensures that, no matter how many times we try to instantiate it, the same object is always returned, thus providing consistency in its use.

What is the Singleton pattern in JavaScript?

In essence, the Singleton pattern ensures that there is only one instance of an object. Every time you try to create a new one, you simply get the object already created. This principle simplifies the management of shared resources such as global settings or single handles.

How to implement it correctly?

The proper way to implement this pattern in JavaScript involves a check in the constructor:

class Singleton  {  constructor()  {    if (Singleton.instance)  {      return Singleton.instance;     }    this.name  = '';    Singleton.instance  = this;    return Singleton.instance;   }  setName(name)  {    this.name  = name;  }const singleton1  = new Singleton();const singleton2  = new Singleton();console.log(singleton1  === singleton2); // true

It is important to remember that this pattern presents the logical condition of checking if the instance already exists: if it exists, it is returned directly, if not, a new one is created.

What is the Factory pattern in JavaScript?

The Factory pattern facilitates the creation of multiple objects of the same type through a common method or function, allowing flexibility and simplicity in your code. It is widely used in modern libraries and tools.

How is the Factory pattern implemented?

The implementation involves creating a class responsible for instantiating new objects:

class Pet  {  constructor(name)  {    this.name  = name;   }}class PetFactory  {  createPet(name)  {    return new Pet(name);  }const factory  = new PetFactory();const pet1  = factory.createPet('Firulais');const pet2  = factory.createPet('Max');console.log(pet1  === pet2); // false

Here we see how Factory helps in the efficient creation of similar but distinct objects.

What is the difference between Singleton and Factory?

While Singleton maintains a single instance of the created object, Factory allows us to generate as many different instances of the same type as we need. They are complementary patterns used according to the situation and need of the design:

  • Singleton ensures uniqueness in the object instance.
  • Factory generates new instances according to specific requirements, maintaining flexibility and customization.

We invite you to leave your comments and questions about these patterns in JavaScript; your participation is valuable to continue delving into relevant topics for your professional development.

Contributions 4

Questions 0

Sort by:

Want to see more contributions, questions and answers from the community?

El singleton: ![](https://refactoring.guru/images/patterns/content/singleton/singleton-comic-1-es.png)
Tengo una duda, 驴no se supone que en el patr贸n singleton el constructor es privado? O 驴esto no aplica para JS? Lo pregunto es porque en TS el constructor lo he visto declarado como privado.
Increible, ni siquiera lei el codigo del singlenton que genero la ia, no dude en que estaria bien, pero cuando lo ley me di cuenta de la falla
a mi juicio creo que responde con claridad, pero si hay objeciones podr铆a ser interesante conocer otros puntos de vista. nota: preguntar en PLATZI: 驴Qu茅 consecuencias tendr铆a integrar ambos patrones (Singleton + Factory) en un mismo sistema para gestionar entidades 煤nicas por tipo, como en un juego (un solo "jefe", m煤ltiples "enemigos")? nota 2: Respuesta en PLATZI Integrar los patrones Singleton y Factory en un sistema para gestionar entidades 煤nicas por tipo, como en un juego, permite controlar instancias de objetos de manera eficiente. El patr贸n Singleton asegura que solo haya una instancia de ciertos objetos, como un "jefe", mientras que el patr贸n Factory puede crear m煤ltiples instancias de objetos como "enemigos". Esto optimiza el uso de recursos y simplifica la gesti贸n de instancias. Sin embargo, es crucial manejar adecuadamente la l贸gica de creaci贸n para evitar problemas de acoplamiento y asegurar que las instancias se mantengan consistentes y accesibles.