如何使用静态关键字通过参数定义单例模式?
[来自here的第二个答案,我试图在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);
[我想在定义new
模式时将Singleton
关键字放在类中。
任何解决我的问题的技巧吗?
感谢。
回答如下: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;
}
如何使用静态关键字通过参数定义单例模式?
[来自here的第二个答案,我试图在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);
[我想在定义new
模式时将Singleton
关键字放在类中。
任何解决我的问题的技巧吗?
感谢。
回答如下: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;
}