如何在Typescript中创建抽象工厂模式? [英] How do I create an abstract factory pattern in Typescript?

查看:133
本文介绍了如何在Typescript中创建抽象工厂模式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在Typescript中实现标准的抽象工厂模式,但是编译器无法协同工作.这是我的代码的简化版本:

I am trying to implement a standard abstract factory pattern in Typescript, but the compiler is not being cooperative. Here is a simplified version of my code:

abstract class Model { }
class User extends Model { }

abstract class ModelFactory<T extends typeof Model> {
   constructor(private modelConstructor: T) {}

   public create(): T {
     return new (this.modelConstructor)();  // ERROR HERE
   }
}
class UserFactory extends ModelFactory<typeof User> {
  constructor() {
    super(User);
  }
}

let user: User;
user  = new UserFactory().create();

但是,当我使用tsc 2.1进行编译时,在上面指出的行上出现了以下错误:

However, when I compile using tsc 2.1, I get the following error at the line indicated above:

model.ts(8,13): error TS2511: Cannot create an instance of the abstract class 'Model'.

如果我删除安全类型并将行转换为此:

If I remove type safety and convert the line to this:

return new (this.modelConstructor as any)();

代码编译无误.但是,这是不幸的.有没有什么方法可以在不使用强制转换的情况下使此代码可编译?如果没有,为什么不呢?

The code is compiled without errors. However, this is unfortunate. Is there any way to make this code compilable without using a cast? And if not, why not?

推荐答案

您应改用以下模式:

abstract class ModelFactory<T extends Model> {
    constructor(private modelConstructor: new () => T) { }

    public create(): T {
        return new (this.modelConstructor)();  // OK!
    }
}

class UserFactory extends ModelFactory<User> {
    constructor() {
        super(User);
    }
}

这篇关于如何在Typescript中创建抽象工厂模式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆