Ad

How To Define Singleton Pattern With Parameter Using Static Keyword?

- 1 answer

According to second answer from here, I'm trying to create Singleton pattern in JS for storing data and invoking its prototypes from the other instances.

A main problem is Singleton doesn't store the data after receives the first instance.

[{…}] 0: {firstName: "John", lastName: "Grand"}

This is how I've done:

export default class Terminal {
    static cache(output) {
        // Singleton
        if (!Terminal.instance) {
            Terminal.instance = new Terminal(output);
        }
        return Terminal.instance;
    }
    constructor(output) {
        // Create an array
        this.logs = [];

        // Switch to an object
        const data = Object.assign({}, output);

        // Add the object to the array
        this.logs.push(data);

        // Inspect
        console.log(this.logs);
    }
}

// instance 1
import Terminal from './terminal.js';
class Person {
    constructor(firstName, lastName, input) {
        this.firstName = firstName;
        this.lastName = lastName;

        // Assign the Singleton
        this.input = input || Terminal.cache(this);
    }
}
let player1 = new Person('John', 'Grand');

// instance 2
import Terminal from './terminal.js';
class Grocery {
    constructor(name, stock, input) {
        this.name = name;
        this.stock = stock;

        // Assign the Singleton
        this.input = input || Terminal.cache(this);
    }
}
let shop1 = new Grocery('Apple', 12);

I want to let the new keyword inside of the class when I define the Singleton pattern.

Any tips to accomplish my problem?

Thanks.

Ad

Answer

The cache() method needs to push output onto the logs array when the object already exists.

    static cache(output) {
        // Singleton
        if (!Terminal.instance) {
            Terminal.instance = new Terminal(output);
        } else {
            Terminal.instance.logs.push(Object.assign({}, output));
        }
        return Terminal.instance;
    }
Ad
source: stackoverflow.com
Ad