網站搜尋

在 Typescript 中,私有(Private)和受保護(Protected)構造函數的用途是什麼


我注意到在 Typescript 中,你可以將建構子定義為任何存取修飾符(private、protected、public)。有人能舉一個有效的例子,說明如何在 Typescript 中使用 private 和 protected 的建構子嗎?

例如,這是一個在 Typescript 中有效的程式碼:

class A
{
    private constructor()
    {
        console.log("hello");
    }
}

答案#1

就像在其他語言中一樣,這個用法的目的是實際上不允許任何人(除了類本身)去實例化這個類。例如,這可能對僅有靜態方法的類有用(在 Typescript 中這是一個罕見的使用情況,因為有更簡單的方法可以做到這一點),或者用於實現簡單的單例模式:

class A
{
    private constructor()
    {
        console.log("hello");
    }

    private static _a :A
    static get(): A{
        return A._a || (A._a = new A())
    }
}

或特殊的初始化需求,需要使用工廠函數。例如異步初始化:

class A
{
    private constructor()
    {
        console.log("hello");
    }

    private init() :Promise<void>{} 
    static async create(): Promise<A>{
        let a = new A()
        await a.init();
        return a;
    }
}

答案#2

這可以用於單例模式。

其中一種方法是完全不讓外部程式碼創建類的實例。取而代之,我們使用靜態存取器:

class SingletonExample {

    private constructor() {
        console.log('Instance created');
    }

    private static _instance: SingletonExample | undefined;

    public prop = 'value';

    public static instance() {
        if (this._instance === undefined) {
            // no error, since the code is inside the class
            this._instance = new SingletonExample();
        }
        return this._instance;
    }

}

const singleton = SingletonExample.instance(); // no error, instance is created
console.log(singleton.prop); // value
const oops = new SingletonExample(); // oops, constructor is private