maj*_*aja 119 singleton typescript
在TypeScript中为类实现Singleton模式的最佳和最方便的方法是什么?(有和没有延迟初始化).
Ale*_*lex 160
从TS 2.0开始,我们就可以在构造函数上定义可见性修饰符,所以现在我们可以像在其他语言中一样使用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;
Run Code Online (Sandbox Code Playgroud)
Rya*_*ugh 83
TypeScript中的Singleton类通常是反模式.您可以简单地使用命名空间.
class Singleton {
/* ... lots of singleton logic ... */
public someMethod() { ... }
}
// Using
var x = Singleton.getInstance();
x.someMethod();
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
cod*_*elt 39
我发现的最好方法是:
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;
}
}
Run Code Online (Sandbox Code Playgroud)
以下是您使用它的方式:
var scoreManager = SingletonClass.getInstance();
scoreManager.setScore(10);
scoreManager.addPoints(1);
scoreManager.removePoints(2);
console.log( scoreManager.getScore() );
Run Code Online (Sandbox Code Playgroud)
http://www.codebelt.com/typescript/typescript-singleton-pattern/
maj*_*aja 22
以下方法创建一个Singleton类,可以像传统类一样exacly使用:
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;
}
Run Code Online (Sandbox Code Playgroud)
每个new Singleton()操作都将返回相同的实例.然而,这可能是用户意外的.
以下示例对用户更透明,但需要使用不同的用法:
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;
}
Run Code Online (Sandbox Code Playgroud)
用法: var obj = Singleton.getInstance();
Rom*_*ert 15
我很惊讶在这里看不到以下模式,实际上看起来非常简单.
// shout.ts
class ShoutSingleton {
helloWorld() { return 'hi'; }
}
export let Shout = new ShoutSingleton();
Run Code Online (Sandbox Code Playgroud)
用法
import { Shout } from './shout';
Shout.helloWorld();
Run Code Online (Sandbox Code Playgroud)
我的解决方案:
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;
}
}
Run Code Online (Sandbox Code Playgroud)
现在构造函数可以是私有的
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());
}
}
Run Code Online (Sandbox Code Playgroud)
你可以使用类表达式(我相信1.6).
var x = new (class {
/* ... lots of singleton logic ... */
public someMethod() { ... }
})();
Run Code Online (Sandbox Code Playgroud)
或者如果您的类需要在内部访问其类型,请使用该名称
var x = new (class Singleton {
/* ... lots of singleton logic ... */
public someMethod(): Singleton { ... }
})();
Run Code Online (Sandbox Code Playgroud)
另一种选择是使用一些静态成员在单例内部使用本地类
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();
Run Code Online (Sandbox Code Playgroud)
将以下6行添加到任何类中,使其成为“ Singleton”。如果您希望通过属性而不是方法来获取实例,请使用Alex答案。
class MySingleton
{
private constructor(){ /* ... */}
private static _instance:MySingleton;
public static getInstance():MySingleton
{
return this._instance||(this._instance = new this());
};
}
Run Code Online (Sandbox Code Playgroud)
var test = MySingleton.getInstance(); // will create the first instance
var test2 = MySingleton.getInstance(); // will return the first instance
alert(test === test2); // true
Run Code Online (Sandbox Code Playgroud)
我想也许使用泛型会更好
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;
}
Run Code Online (Sandbox Code Playgroud)
如何使用
第1步
class MapManager extends Singleton<MapManager>{
//do something
public init():void{ //do }
}
Run Code Online (Sandbox Code Playgroud)
第2步
MapManager.Instance(MapManager).init();
Run Code Online (Sandbox Code Playgroud)