Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

207
Visualizações
Node Singleton Use

The author of this article uses singletons for the service layer in this example Node api:

https://html5hive.org/how-to-create-rest-api-with-node-js-and-express/

He states, "We only want there to ever be one instance of our player service, so instead of exporting the class itself, we’ll export a new instance of it. Module files in node are only ever executed once, so this effectively gives us a singleton."

'use strict';

var uuid = require('node-uuid');

class PlayersService {
    constructor() {
        this.players = [];
    }

    getPlayers() {
        return this.players;
    }

    getSinglePlayer(playerId) {
        var player = this.players.filter(p => p.id === playerId)[0];

        return player || null;
    }

    addPlayer(info) {
        // prevent a bit of bad/duplicate data
        if (!info || this.players.filter(p => (p.firstName === info.firstName && p.lastName === info.lastName)).length > 0) {
            return false;
        }

        info.id = uuid.v4();

        this.players.push(info);
        return true;
    }

    updatePlayer(playerId, info) {
        var player = this.getSinglePlayer(playerId);
        if (player) {
            player.firstName = info.firstName ? info.firstName : player.firstName;
            player.lastName = info.lastName ? info.lastName : player.lastName;
            player.displayName = info.displayName ? info.displayName : player.displayName;

            return true;
        }
        return false;
    }
}

module.exports = new PlayersService();

Which seems reasonable since the function of these services is to provide the same implementation for the controllers that use them.

However, in this post:

On Design Patterns: When to use the Singleton?

the poster asks for a legitimate use case for singletons other than a Logger class. Several people responded to his question by saying that singletons should never be used.

But isn't the use of singletons for services like the one I've copied here a legitimate use case and a best practice so that you are not creating multiple instances that provide the same implementation? Thanks.

over 4 years ago · Santiago Trujillo
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda