使用typescript/javascript我已經建立了一個單例集合。
然而,為了重構和抽象實作,我嘗試準備一個類來實作該單例邏輯并讓它們擴展。這對我來說顯然是幼稚的,因為這種情況會導致建構式出現問題并且似乎不可行。
所以我的問題是,是否可以優雅地將單例行為應用于類/物件的集合?
在下面的代碼中,出于可讀性考慮,將單例邏輯抽象出來會很好。此外,具體來說,我想強制此集合中的其他類,因為它們是由貢獻者添加的,以將它們實作為單例。通過“插入”一些抽象的擴展類或某種包裝器來做到這一點會更好一些。
class Car {
/* Singleton Implementation Start */
private static _instance: Car;
private constructor() {}
public static getInstance(): Car {
if (!Car._instance) {
Car._instance = new Car();
}
return Car._instance;
}
/* Singleton Implementation End */
private _name = "Audi"
private _color = 'red';
private _maxSpeed = 150;
drive(){
console.log(`WOW! You are riding your cool ${this._color} ${this._name} at ${150} kmh!` )
}
paint(color: string){
this._color = color;
}
}
class Plane {
/* Singleton Implementation Start */
private static _instance: Plane;
private constructor() {}
public static getInstance(): Plane {
if (!Plane._instance) {
Plane._instance = new Plane();
}
return Plane._instance;
}
/* Singleton Implementation End */
private _motors = 4;
private _maxSpeed = 550;
fly(){
console.log(`WOW! You are flying your plane with roaring ${_motors} motors at ${150} kmh!` )
}
}
uj5u.com熱心網友回復:
如果我們創建一個帶有泛型的工廠函式:
function Singleton<T>() {
return class Singleton {
static instance: T; // using native private fields
protected constructor() {}
public static getInstance(): T {
if (!this.instance) this.instance = new this() as T;
return this.instance;
}
}
}
然后我們可以擴展回傳的類并提供泛型作為類本身:
class Car extends Singleton<Car>() {
private _name = "Audi"
private _color = 'red';
private _maxSpeed = 150;
drive(){
console.log(`WOW! You are riding your cool ${this._color} ${this._name} at ${150} kmh!` )
}
paint(color: string){
this._color = color;
}
}
這必須通過函式來??完成,因為靜態成員不能參考類的型別引數。此外,缺點是您不能擁有任何私有或受保護的成員。
操場
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/525940.html
上一篇:在Python中理解鏈表的問題
下一篇:類和無狀態小部件
