我注意到在Typescript中,您可以将构造函数定义为具有任何访问修饰符(私有,受保护,公共)。有人可以给出一个有效的示例,如何在Typescript中使用私有和受保护的构造函数吗?
例如,这是打字稿中的有效代码:
class A
{
private constructor()
{
console.log("hello");
}
}
Run Code Online (Sandbox Code Playgroud)
就像其他语言一样,此用法实际上是不允许任何人(类本身除外)实例化该类。例如,这对于仅具有静态方法的类(在Typescript中是一种罕见的用例,因为有更简单的方法可以这样做)可能有用,或者允许简单的单例实现:
class A
{
private constructor()
{
console.log("hello");
}
private static _a :A
static get(): A{
return A._a || (A._a = new A())
}
}
Run Code Online (Sandbox Code Playgroud)
或特殊的初始化要求,例如async init:
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;
}
}
Run Code Online (Sandbox Code Playgroud)
这可以用于单例模式。
一种解决方法是根本不让外部代码创建该类的实例。相反,我们使用静态访问器:
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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5754 次 |
| 最近记录: |