如何在 TypeScript 中定义单例
How to define Singleton in TypeScript
在 TypeScript 中为 class 实现单例模式的最佳和最方便的方法是什么? (有和没有惰性初始化)。
以下方法创建了一个 Singleton class,它可以像传统的 class 一样使用:
class Singleton {
private static instance: Singleton;
//Assign "new Singleton()" here to avoid lazy initialisation
constructor() {
if (Singleton.instance) {
return Singleton.instance;
}
this. member = 0;
Singleton.instance = this;
}
member: number;
}
每个 new Singleton()
操作将 return 相同的实例。然而,这可能是用户意想不到的。
以下示例对用户更透明,但需要不同的用法:
class Singleton {
private static instance: Singleton;
//Assign "new Singleton()" here to avoid lazy initialisation
constructor() {
if (Singleton.instance) {
throw new Error("Error - use Singleton.getInstance()");
}
this.member = 0;
}
static getInstance(): Singleton {
Singleton.instance = Singleton.instance || new Singleton();
return Singleton.instance;
}
member: number;
}
用法:var obj = Singleton.getInstance();
TypeScript 中的单例 类 通常是一种反模式。您可以简单地使用 namespaces 代替。
无用的单例模式
class Singleton {
/* ... lots of singleton logic ... */
public someMethod() { ... }
}
// Using
var x = Singleton.getInstance();
x.someMethod();
等效命名空间
export namespace Singleton {
export function someMethod() { ... }
}
// Usage
import { SingletonInstance } from "path/to/Singleton";
SingletonInstance.someMethod();
var x = SingletonInstance; // If you need to alias it for some reason
我找到的最佳方法是:
class SingletonClass {
private static _instance:SingletonClass = new SingletonClass();
private _score:number = 0;
constructor() {
if(SingletonClass._instance){
throw new Error("Error: Instantiation failed: Use SingletonClass.getInstance() instead of new.");
}
SingletonClass._instance = this;
}
public static getInstance():SingletonClass
{
return SingletonClass._instance;
}
public setScore(value:number):void
{
this._score = value;
}
public getScore():number
{
return this._score;
}
public addPoints(value:number):void
{
this._score += value;
}
public removePoints(value:number):void
{
this._score -= value;
}
}
以下是使用方法:
var scoreManager = SingletonClass.getInstance();
scoreManager.setScore(10);
scoreManager.addPoints(1);
scoreManager.removePoints(2);
console.log( scoreManager.getScore() );
https://codebelt.github.io/blog/typescript/typescript-singleton-pattern/
这可能是在 typescript 中制作单例的最长过程,但在较大的应用程序中对我来说效果更好。
首先你需要一个单例class,比方说,"./utils/Singleton.ts":
module utils {
export class Singleton {
private _initialized: boolean;
private _setSingleton(): void {
if (this._initialized) throw Error('Singleton is already initialized.');
this._initialized = true;
}
get setSingleton() { return this._setSingleton; }
}
}
现在假设您需要一个 Router 单例 "./navigation/Router.ts":
/// <reference path="../utils/Singleton.ts" />
module navigation {
class RouterClass extends utils.Singleton {
// NOTICE RouterClass extends from utils.Singleton
// and that it isn't exportable.
private _init(): void {
// This method will be your "construtor" now,
// to avoid double initialization, don't forget
// the parent class setSingleton method!.
this.setSingleton();
// Initialization stuff.
}
// Expose _init method.
get init { return this.init; }
}
// THIS IS IT!! Export a new RouterClass, that no
// one can instantiate ever again!.
export var Router: RouterClass = new RouterClass();
}
很好!,现在在您需要的地方初始化或导入:
/// <reference path="./navigation/Router.ts" />
import router = navigation.Router;
router.init();
router.init(); // Throws error!.
以这种方式处理单例的好处是您仍然可以使用 typescript classes 的所有优点,它为您提供了很好的智能感知,单例逻辑以某种方式保持分离,并且如果需要可以轻松删除。
您可以为此使用 class 表达式(我相信从 1.6 开始)。
var x = new (class {
/* ... lots of singleton logic ... */
public someMethod() { ... }
})();
如果您的 class 需要在内部访问其类型,则使用名称
var x = new (class Singleton {
/* ... lots of singleton logic ... */
public someMethod(): Singleton { ... }
})();
另一种选择是使用一些静态成员
在你的单例中使用本地class
class Singleton {
private static _instance;
public static get instance() {
class InternalSingleton {
someMethod() { }
//more singleton logic
}
if(!Singleton._instance) {
Singleton._instance = new InternalSingleton();
}
return <InternalSingleton>Singleton._instance;
}
}
var x = Singleton.instance;
x.someMethod();
这是使用 IFFE 的更传统 javascript 方法的另一种方法:
module App.Counter {
export var Instance = (() => {
var i = 0;
return {
increment: (): void => {
i++;
},
getCount: (): number => {
return i;
}
}
})();
}
module App {
export function countStuff() {
App.Counter.Instance.increment();
App.Counter.Instance.increment();
alert(App.Counter.Instance.getCount());
}
}
App.countStuff();
查看一个demo
将以下 6 行添加到任何 class 使其成为 "Singleton".
class MySingleton
{
private constructor(){ /* ... */}
private static _instance: MySingleton;
public static getInstance(): MySingleton
{
return this._instance || (this._instance = new this());
};
}
var test = MySingleton.getInstance(); // will create the first instance
var test2 = MySingleton.getInstance(); // will return the first instance
alert(test === test2); // true
[编辑]:如果您更喜欢通过 属性 而不是方法来获取实例,请使用 Alex answer。
从 TS 2.0 开始,我们可以定义 visibility modifiers on constructors,所以现在我们可以像在其他语言中一样在 TypeScript 中使用单例。
给出的例子:
class MyClass
{
private static _instance: MyClass;
private constructor()
{
//...
}
public static get Instance()
{
// Do you need arguments? Make it a regular static method instead.
return this._instance || (this._instance = new this());
}
}
const myClassInstance = MyClass.Instance;
感谢@Drenai 指出如果您使用原始编译的 javascript 编写代码,您将无法防止多重实例化,因为 TS 的约束消失并且构造函数不会被隐藏。
另一种选择是在您的模块中使用 Symbols。这样你就可以保护你的 class,即使你的 API 的最终用户使用正常的 Javascript:
let _instance = Symbol();
export default class Singleton {
constructor(singletonToken) {
if (singletonToken !== _instance) {
throw new Error("Cannot instantiate directly.");
}
//Init your class
}
static get instance() {
return this[_instance] || (this[_instance] = new Singleton(_singleton))
}
public myMethod():string {
return "foo";
}
}
用法:
var str:string = Singleton.instance.myFoo();
如果用户正在使用您编译的 API js 文件,如果他尝试手动实例化您的 class:
也会出现错误
// PLAIN JAVASCRIPT:
var instance = new Singleton(); //Error the argument singletonToken !== _instance symbol
我的解决方案:
export default class Singleton {
private static _instance: Singleton = new Singleton();
constructor() {
if (Singleton._instance)
throw new Error("Use Singleton.instance");
Singleton._instance = this;
}
static get instance() {
return Singleton._instance;
}
}
2021 年更新
现在构造函数可以是私有的
export default class Singleton {
private static _instance?: Singleton;
private constructor() {
if (Singleton._instance)
throw new Error("Use Singleton.instance instead of new.");
Singleton._instance = this;
}
static get instance() {
return Singleton._instance ?? (Singleton._instance = new Singleton());
}
}
namespace MySingleton {
interface IMySingleton {
doSomething(): void;
}
class MySingleton implements IMySingleton {
private usePrivate() { }
doSomething() {
this.usePrivate();
}
}
export var Instance: IMySingleton = new MySingleton();
}
与 Ryan Cavanaugh 接受的答案不同,我们可以通过这种方式应用接口。
我很惊讶这里没有看到下面的模式,实际上看起来很简单。
// shout.ts
class ShoutSingleton {
helloWorld() { return 'hi'; }
}
export let Shout = new ShoutSingleton();
用法
import { Shout } from './shout';
Shout.helloWorld();
在 Typescript 中,不一定要遵循 new instance()
单例方法。导入的、无构造函数的静态 class 也可以同样工作。
考虑:
export class YourSingleton {
public static foo:bar;
public static initialise(_initVars:any):void {
YourSingleton.foo = _initvars.foo;
}
public static doThing():bar {
return YourSingleton.foo
}
}
您可以导入 class 并在任何其他 class 中引用 YourSingleton.doThing()
。但请记住,因为这是一个静态的 class,它没有构造函数,所以我通常使用从导入单例的 class 调用的 intialise()
方法:
import {YourSingleton} from 'singleton.ts';
YourSingleton.initialise(params);
let _result:bar = YourSingleton.doThing();
不要忘记在静态 class 中,每个方法和变量也需要是静态的,因此您可以使用完整的 class 名称 [=16] 而不是 this
=].
我想也许使用泛型会更好
class Singleton<T>{
public static Instance<T>(c: {new(): T; }) : T{
if (this._instance == null){
this._instance = new c();
}
return this._instance;
}
private static _instance = null;
}
如何使用
第一步
class MapManager extends Singleton<MapManager>{
//do something
public init():void{ //do }
}
第 2 步
MapManager.Instance(MapManager).init();
您还可以使用函数 Object.Freeze()。简单易行:
class Singleton {
instance: any = null;
data: any = {} // store data in here
constructor() {
if (!this.instance) {
this.instance = this;
}
return this.instance
}
}
const singleton: Singleton = new Singleton();
Object.freeze(singleton);
export default singleton;
不是纯单例(初始化可能不懒惰),但在 namespace
s 的帮助下有类似的模式。
namespace MyClass
{
class _MyClass
{
...
}
export const instance: _MyClass = new _MyClass();
}
访问单例对象:
MyClass.instance
这是最简单的方法
class YourSingletoneClass {
private static instance: YourSingletoneClass;
private constructor(public ifYouHaveAnyParams: string) {
}
static getInstance() {
if(!YourSingletoneClass.instance) {
YourSingletoneClass.instance = new YourSingletoneClass('If you have any params');
}
return YourSingletoneClass.instance;
}
}
我发现了一个 Typescript 编译器完全可以接受的新版本,我认为它更好,因为它不需要不断调用 getInstance()
方法。
import express, { Application } from 'express';
export class Singleton {
// Define your props here
private _express: Application = express();
private static _instance: Singleton;
constructor() {
if (Singleton._instance) {
return Singleton._instance;
}
// You don't have an instance, so continue
// Remember, to set the _instance property
Singleton._instance = this;
}
}
这确实有一个不同的缺点。如果你的 Singleton
确实有任何属性,那么 Typescript 编译器将抛出一个合适的值,除非你用一个值初始化它们。这就是为什么我在我的示例 class 中包含一个 _express
属性 因为除非你用一个值初始化它,即使你稍后在构造函数中分配它,Typescript 也会认为它没有定义。这可以通过禁用严格模式来解决,但如果可能的话我不想这样做。我还应该指出这种方法的另一个缺点,因为构造函数实际上是被调用的,每次调用它时都会在技术上创建另一个实例,但无法访问。理论上,这可能会导致内存泄漏。
在搜索了这个线程并尝试了上面的所有选项之后 - 我选择了一个可以使用适当的构造函数创建的单例:
export default class Singleton {
private static _instance: Singleton
public static get instance(): Singleton {
return Singleton._instance
}
constructor(...args: string[]) {
// Initial setup
Singleton._instance = this
}
work() { /* example */ }
}
需要初始设置(在 main.ts
或 index.ts
中),
可以轻松实现
new Singleton(/* PARAMS */)
然后,在您的代码中的任何位置,只需调用 Singleton.instnace
;在这种情况下,要完成 work
,我会调用 Singleton.instance.work()
实施 classic 模式后
class Singleton {
private instance: Singleton;
private constructor() {}
public getInstance() {
if (!this.instance) {
this.instance = new Singleton();
}
return this.instance;
}
}
我意识到如果您想让其他 class 也成为单身人士,那将毫无用处。它不可扩展。你必须为每个 class 想成为单身人士的人写单身人士的东西。
救援装饰器。
@singleton
class MyClassThatIsSingletonToo {}
装饰器可以自己写,也可以从npm拿来。我发现 this proxy-based implementation from @keenondrums/singleton 包足够整洁。
让我们举个例子,我想创建单例 class 通过它我将能够创建客户端的连接然后我想在任何地方都使用同一个连接的客户端。
import nats, { Stan } from 'node-nats-streaming';
class NatsWrapper {
private _client?: Stan;
get client() {
if (!this._client) {
throw new Error('Cannot access NATS client before connecting');
}
return this._client;
}
connect(clusterId: string, clientId: string, url: string) {
this._client = nats.connect(clusterId, clientId, { url });
return new Promise((resolve, reject) => {
this.client.on('connect', (result) => {
console.log('Connected to NATS');
resolve(result);
});
this.client.on('error', (err) => {
reject(err);
});
});
}
}
// since we create and export the instace, it will act like a singleton
export const natsWrapper = new NatsWrapper();
现在,首先在您的 index.ts/app.ts 文件中创建连接,然后您只需在任何地方导入即可访问同一个客户端
index.ts
await natsWrapper.connect(
'ticketing',
'client_id_random_str',
'http://nats-srv:4222'
);
someFile.ts
import { natsWrapper } from '../nats-wrapper';
const abc = () =>{
console.log(natsWrapper.client)
}
我一直在努力寻找一个合适的解决方案来在 typescript 中声明单例模式 class。
我认为下面是更实用的解决方案。
class MySingletonClass {
public now:Date = new Date();
public arg:string;
constructor(arg:string) {
this.arg = arg;
// Make singleton
if ('instance' in MySingletonClass) return Object.getOwnPropertyDescriptor(MySingletonClass, 'instance')?.value;
Object.assign(MySingletonClass, { instance: this });
}
}
const a = new MySingletonClass('a');
console.log(a);
const b = new MySingletonClass('b');
console.log(b);
console.log('a === b', a === b);
console.log('a.now === b.now', a.now === b.now);
/**
* The Singleton class defines the `getInstance` method that lets clients access
* the unique singleton instance.
*/
class Singleton {
private static instance: Singleton;
/**
* The Singleton's constructor should always be private to prevent direct
* construction calls with the `new` operator.
*/
private constructor() { }
/**
* The static method that controls the access to the singleton instance.
*
* This implementation let you subclass the Singleton class while keeping
* just one instance of each subclass around.
*/
public static getInstance(): Singleton {
if (!Singleton.instance) {
Singleton.instance = new Singleton();
}
return Singleton.instance;
}
/**
* Finally, any singleton should define some business logic, which can be
* executed on its instance.
*/
public someBusinessLogic() {
// ...
}
}
/**
* The client code.
*/
function clientCode() {
const s1 = Singleton.getInstance();
const s2 = Singleton.getInstance();
if (s1 === s2) {
console.log('Singleton works, both variables contain the same instance.');
} else {
console.log('Singleton failed, variables contain different instances.');
}
}
clientCode();
在 TypeScript 中为 class 实现单例模式的最佳和最方便的方法是什么? (有和没有惰性初始化)。
以下方法创建了一个 Singleton class,它可以像传统的 class 一样使用:
class Singleton {
private static instance: Singleton;
//Assign "new Singleton()" here to avoid lazy initialisation
constructor() {
if (Singleton.instance) {
return Singleton.instance;
}
this. member = 0;
Singleton.instance = this;
}
member: number;
}
每个 new Singleton()
操作将 return 相同的实例。然而,这可能是用户意想不到的。
以下示例对用户更透明,但需要不同的用法:
class Singleton {
private static instance: Singleton;
//Assign "new Singleton()" here to avoid lazy initialisation
constructor() {
if (Singleton.instance) {
throw new Error("Error - use Singleton.getInstance()");
}
this.member = 0;
}
static getInstance(): Singleton {
Singleton.instance = Singleton.instance || new Singleton();
return Singleton.instance;
}
member: number;
}
用法:var obj = Singleton.getInstance();
TypeScript 中的单例 类 通常是一种反模式。您可以简单地使用 namespaces 代替。
无用的单例模式
class Singleton {
/* ... lots of singleton logic ... */
public someMethod() { ... }
}
// Using
var x = Singleton.getInstance();
x.someMethod();
等效命名空间
export namespace Singleton {
export function someMethod() { ... }
}
// Usage
import { SingletonInstance } from "path/to/Singleton";
SingletonInstance.someMethod();
var x = SingletonInstance; // If you need to alias it for some reason
我找到的最佳方法是:
class SingletonClass {
private static _instance:SingletonClass = new SingletonClass();
private _score:number = 0;
constructor() {
if(SingletonClass._instance){
throw new Error("Error: Instantiation failed: Use SingletonClass.getInstance() instead of new.");
}
SingletonClass._instance = this;
}
public static getInstance():SingletonClass
{
return SingletonClass._instance;
}
public setScore(value:number):void
{
this._score = value;
}
public getScore():number
{
return this._score;
}
public addPoints(value:number):void
{
this._score += value;
}
public removePoints(value:number):void
{
this._score -= value;
}
}
以下是使用方法:
var scoreManager = SingletonClass.getInstance();
scoreManager.setScore(10);
scoreManager.addPoints(1);
scoreManager.removePoints(2);
console.log( scoreManager.getScore() );
https://codebelt.github.io/blog/typescript/typescript-singleton-pattern/
这可能是在 typescript 中制作单例的最长过程,但在较大的应用程序中对我来说效果更好。
首先你需要一个单例class,比方说,"./utils/Singleton.ts":
module utils {
export class Singleton {
private _initialized: boolean;
private _setSingleton(): void {
if (this._initialized) throw Error('Singleton is already initialized.');
this._initialized = true;
}
get setSingleton() { return this._setSingleton; }
}
}
现在假设您需要一个 Router 单例 "./navigation/Router.ts":
/// <reference path="../utils/Singleton.ts" />
module navigation {
class RouterClass extends utils.Singleton {
// NOTICE RouterClass extends from utils.Singleton
// and that it isn't exportable.
private _init(): void {
// This method will be your "construtor" now,
// to avoid double initialization, don't forget
// the parent class setSingleton method!.
this.setSingleton();
// Initialization stuff.
}
// Expose _init method.
get init { return this.init; }
}
// THIS IS IT!! Export a new RouterClass, that no
// one can instantiate ever again!.
export var Router: RouterClass = new RouterClass();
}
很好!,现在在您需要的地方初始化或导入:
/// <reference path="./navigation/Router.ts" />
import router = navigation.Router;
router.init();
router.init(); // Throws error!.
以这种方式处理单例的好处是您仍然可以使用 typescript classes 的所有优点,它为您提供了很好的智能感知,单例逻辑以某种方式保持分离,并且如果需要可以轻松删除。
您可以为此使用 class 表达式(我相信从 1.6 开始)。
var x = new (class {
/* ... lots of singleton logic ... */
public someMethod() { ... }
})();
如果您的 class 需要在内部访问其类型,则使用名称
var x = new (class Singleton {
/* ... lots of singleton logic ... */
public someMethod(): Singleton { ... }
})();
另一种选择是使用一些静态成员
在你的单例中使用本地classclass Singleton {
private static _instance;
public static get instance() {
class InternalSingleton {
someMethod() { }
//more singleton logic
}
if(!Singleton._instance) {
Singleton._instance = new InternalSingleton();
}
return <InternalSingleton>Singleton._instance;
}
}
var x = Singleton.instance;
x.someMethod();
这是使用 IFFE 的更传统 javascript 方法的另一种方法:
module App.Counter {
export var Instance = (() => {
var i = 0;
return {
increment: (): void => {
i++;
},
getCount: (): number => {
return i;
}
}
})();
}
module App {
export function countStuff() {
App.Counter.Instance.increment();
App.Counter.Instance.increment();
alert(App.Counter.Instance.getCount());
}
}
App.countStuff();
查看一个demo
将以下 6 行添加到任何 class 使其成为 "Singleton".
class MySingleton
{
private constructor(){ /* ... */}
private static _instance: MySingleton;
public static getInstance(): MySingleton
{
return this._instance || (this._instance = new this());
};
}
var test = MySingleton.getInstance(); // will create the first instance
var test2 = MySingleton.getInstance(); // will return the first instance
alert(test === test2); // true
[编辑]:如果您更喜欢通过 属性 而不是方法来获取实例,请使用 Alex answer。
从 TS 2.0 开始,我们可以定义 visibility modifiers on constructors,所以现在我们可以像在其他语言中一样在 TypeScript 中使用单例。
给出的例子:
class MyClass
{
private static _instance: MyClass;
private constructor()
{
//...
}
public static get Instance()
{
// Do you need arguments? Make it a regular static method instead.
return this._instance || (this._instance = new this());
}
}
const myClassInstance = MyClass.Instance;
感谢@Drenai 指出如果您使用原始编译的 javascript 编写代码,您将无法防止多重实例化,因为 TS 的约束消失并且构造函数不会被隐藏。
另一种选择是在您的模块中使用 Symbols。这样你就可以保护你的 class,即使你的 API 的最终用户使用正常的 Javascript:
let _instance = Symbol();
export default class Singleton {
constructor(singletonToken) {
if (singletonToken !== _instance) {
throw new Error("Cannot instantiate directly.");
}
//Init your class
}
static get instance() {
return this[_instance] || (this[_instance] = new Singleton(_singleton))
}
public myMethod():string {
return "foo";
}
}
用法:
var str:string = Singleton.instance.myFoo();
如果用户正在使用您编译的 API js 文件,如果他尝试手动实例化您的 class:
也会出现错误// PLAIN JAVASCRIPT:
var instance = new Singleton(); //Error the argument singletonToken !== _instance symbol
我的解决方案:
export default class Singleton {
private static _instance: Singleton = new Singleton();
constructor() {
if (Singleton._instance)
throw new Error("Use Singleton.instance");
Singleton._instance = this;
}
static get instance() {
return Singleton._instance;
}
}
2021 年更新
现在构造函数可以是私有的
export default class Singleton {
private static _instance?: Singleton;
private constructor() {
if (Singleton._instance)
throw new Error("Use Singleton.instance instead of new.");
Singleton._instance = this;
}
static get instance() {
return Singleton._instance ?? (Singleton._instance = new Singleton());
}
}
namespace MySingleton {
interface IMySingleton {
doSomething(): void;
}
class MySingleton implements IMySingleton {
private usePrivate() { }
doSomething() {
this.usePrivate();
}
}
export var Instance: IMySingleton = new MySingleton();
}
与 Ryan Cavanaugh 接受的答案不同,我们可以通过这种方式应用接口。
我很惊讶这里没有看到下面的模式,实际上看起来很简单。
// shout.ts
class ShoutSingleton {
helloWorld() { return 'hi'; }
}
export let Shout = new ShoutSingleton();
用法
import { Shout } from './shout';
Shout.helloWorld();
在 Typescript 中,不一定要遵循 new instance()
单例方法。导入的、无构造函数的静态 class 也可以同样工作。
考虑:
export class YourSingleton {
public static foo:bar;
public static initialise(_initVars:any):void {
YourSingleton.foo = _initvars.foo;
}
public static doThing():bar {
return YourSingleton.foo
}
}
您可以导入 class 并在任何其他 class 中引用 YourSingleton.doThing()
。但请记住,因为这是一个静态的 class,它没有构造函数,所以我通常使用从导入单例的 class 调用的 intialise()
方法:
import {YourSingleton} from 'singleton.ts';
YourSingleton.initialise(params);
let _result:bar = YourSingleton.doThing();
不要忘记在静态 class 中,每个方法和变量也需要是静态的,因此您可以使用完整的 class 名称 [=16] 而不是 this
=].
我想也许使用泛型会更好
class Singleton<T>{
public static Instance<T>(c: {new(): T; }) : T{
if (this._instance == null){
this._instance = new c();
}
return this._instance;
}
private static _instance = null;
}
如何使用
第一步
class MapManager extends Singleton<MapManager>{
//do something
public init():void{ //do }
}
第 2 步
MapManager.Instance(MapManager).init();
您还可以使用函数 Object.Freeze()。简单易行:
class Singleton {
instance: any = null;
data: any = {} // store data in here
constructor() {
if (!this.instance) {
this.instance = this;
}
return this.instance
}
}
const singleton: Singleton = new Singleton();
Object.freeze(singleton);
export default singleton;
不是纯单例(初始化可能不懒惰),但在 namespace
s 的帮助下有类似的模式。
namespace MyClass
{
class _MyClass
{
...
}
export const instance: _MyClass = new _MyClass();
}
访问单例对象:
MyClass.instance
这是最简单的方法
class YourSingletoneClass {
private static instance: YourSingletoneClass;
private constructor(public ifYouHaveAnyParams: string) {
}
static getInstance() {
if(!YourSingletoneClass.instance) {
YourSingletoneClass.instance = new YourSingletoneClass('If you have any params');
}
return YourSingletoneClass.instance;
}
}
我发现了一个 Typescript 编译器完全可以接受的新版本,我认为它更好,因为它不需要不断调用 getInstance()
方法。
import express, { Application } from 'express';
export class Singleton {
// Define your props here
private _express: Application = express();
private static _instance: Singleton;
constructor() {
if (Singleton._instance) {
return Singleton._instance;
}
// You don't have an instance, so continue
// Remember, to set the _instance property
Singleton._instance = this;
}
}
这确实有一个不同的缺点。如果你的 Singleton
确实有任何属性,那么 Typescript 编译器将抛出一个合适的值,除非你用一个值初始化它们。这就是为什么我在我的示例 class 中包含一个 _express
属性 因为除非你用一个值初始化它,即使你稍后在构造函数中分配它,Typescript 也会认为它没有定义。这可以通过禁用严格模式来解决,但如果可能的话我不想这样做。我还应该指出这种方法的另一个缺点,因为构造函数实际上是被调用的,每次调用它时都会在技术上创建另一个实例,但无法访问。理论上,这可能会导致内存泄漏。
在搜索了这个线程并尝试了上面的所有选项之后 - 我选择了一个可以使用适当的构造函数创建的单例:
export default class Singleton {
private static _instance: Singleton
public static get instance(): Singleton {
return Singleton._instance
}
constructor(...args: string[]) {
// Initial setup
Singleton._instance = this
}
work() { /* example */ }
}
需要初始设置(在 main.ts
或 index.ts
中),
可以轻松实现
new Singleton(/* PARAMS */)
然后,在您的代码中的任何位置,只需调用 Singleton.instnace
;在这种情况下,要完成 work
,我会调用 Singleton.instance.work()
实施 classic 模式后
class Singleton {
private instance: Singleton;
private constructor() {}
public getInstance() {
if (!this.instance) {
this.instance = new Singleton();
}
return this.instance;
}
}
我意识到如果您想让其他 class 也成为单身人士,那将毫无用处。它不可扩展。你必须为每个 class 想成为单身人士的人写单身人士的东西。
救援装饰器。
@singleton
class MyClassThatIsSingletonToo {}
装饰器可以自己写,也可以从npm拿来。我发现 this proxy-based implementation from @keenondrums/singleton 包足够整洁。
让我们举个例子,我想创建单例 class 通过它我将能够创建客户端的连接然后我想在任何地方都使用同一个连接的客户端。
import nats, { Stan } from 'node-nats-streaming';
class NatsWrapper {
private _client?: Stan;
get client() {
if (!this._client) {
throw new Error('Cannot access NATS client before connecting');
}
return this._client;
}
connect(clusterId: string, clientId: string, url: string) {
this._client = nats.connect(clusterId, clientId, { url });
return new Promise((resolve, reject) => {
this.client.on('connect', (result) => {
console.log('Connected to NATS');
resolve(result);
});
this.client.on('error', (err) => {
reject(err);
});
});
}
}
// since we create and export the instace, it will act like a singleton
export const natsWrapper = new NatsWrapper();
现在,首先在您的 index.ts/app.ts 文件中创建连接,然后您只需在任何地方导入即可访问同一个客户端
index.ts
await natsWrapper.connect(
'ticketing',
'client_id_random_str',
'http://nats-srv:4222'
);
someFile.ts
import { natsWrapper } from '../nats-wrapper';
const abc = () =>{
console.log(natsWrapper.client)
}
我一直在努力寻找一个合适的解决方案来在 typescript 中声明单例模式 class。
我认为下面是更实用的解决方案。
class MySingletonClass {
public now:Date = new Date();
public arg:string;
constructor(arg:string) {
this.arg = arg;
// Make singleton
if ('instance' in MySingletonClass) return Object.getOwnPropertyDescriptor(MySingletonClass, 'instance')?.value;
Object.assign(MySingletonClass, { instance: this });
}
}
const a = new MySingletonClass('a');
console.log(a);
const b = new MySingletonClass('b');
console.log(b);
console.log('a === b', a === b);
console.log('a.now === b.now', a.now === b.now);
/**
* The Singleton class defines the `getInstance` method that lets clients access
* the unique singleton instance.
*/
class Singleton {
private static instance: Singleton;
/**
* The Singleton's constructor should always be private to prevent direct
* construction calls with the `new` operator.
*/
private constructor() { }
/**
* The static method that controls the access to the singleton instance.
*
* This implementation let you subclass the Singleton class while keeping
* just one instance of each subclass around.
*/
public static getInstance(): Singleton {
if (!Singleton.instance) {
Singleton.instance = new Singleton();
}
return Singleton.instance;
}
/**
* Finally, any singleton should define some business logic, which can be
* executed on its instance.
*/
public someBusinessLogic() {
// ...
}
}
/**
* The client code.
*/
function clientCode() {
const s1 = Singleton.getInstance();
const s2 = Singleton.getInstance();
if (s1 === s2) {
console.log('Singleton works, both variables contain the same instance.');
} else {
console.log('Singleton failed, variables contain different instances.');
}
}
clientCode();