如何使用 static 关键字定义带参数的单例模式?
How to define Singleton pattern with parameter using static keyword?
根据 的第二个回答,我正在尝试在 JS 中创建 Singleton
模式来存储数据并从其他实例调用其原型。
一个主要问题是Singleton
在收到第一个实例后不存储数据。
[{…}]
0: {firstName: "John", lastName: "Grand"}
我是这样做的:
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);
我想在定义 Singleton
模式时让 new
关键字位于 class 中。
有什么技巧可以解决我的问题吗?
谢谢。
当对象已经存在时,cache()
方法需要将 output
推入 logs
数组。
static cache(output) {
// Singleton
if (!Terminal.instance) {
Terminal.instance = new Terminal(output);
} else {
Terminal.instance.logs.push(Object.assign({}, output));
}
return Terminal.instance;
}
根据 Singleton
模式来存储数据并从其他实例调用其原型。
一个主要问题是Singleton
在收到第一个实例后不存储数据。
[{…}] 0: {firstName: "John", lastName: "Grand"}
我是这样做的:
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);
我想在定义 Singleton
模式时让 new
关键字位于 class 中。
有什么技巧可以解决我的问题吗?
谢谢。
当对象已经存在时,cache()
方法需要将 output
推入 logs
数组。
static cache(output) {
// Singleton
if (!Terminal.instance) {
Terminal.instance = new Terminal(output);
} else {
Terminal.instance.logs.push(Object.assign({}, output));
}
return Terminal.instance;
}