我的应用程序利用工厂帮手来配置各种对象。每个工厂都实现一个接口,可以对其进行模拟以辅助测试。传统上,每个工厂都是实现该接口的类:
const displayExtraUserInfo = (params) => {
document.getElementById("btn-birthdate").addEventListener("click", ()=> {
displayBirthdate(params)
})
document.getElementById("btn-phone").addEventListener("click", () => {
displayPhone(params)
})
document.getElementById("btn-address").addEventListener("click", () => {
displayAddress(params)
})
}
可以实例化 interface IRequestFactory {
create(event: AWSLambda.APIGatewayProxyEvent): IRequest
}
class RealRequestFactory implements IRequestFactory {
public create(event: AWSLambda.APIGatewayProxyEvent): RealRequest {
return new RealRequest(event)
}
}
class MockRequestFactory implements IRequestFactory {
public create(event: AWSLambda.APIGatewayProxyEvent): MockRequest {
return new MockRequest(event)
}
}
或RealRequestFactory
并将其作为依赖项注入到其他类中。但是,TypeScript允许我们将任何内容声明为接口类型,因此可以做到这一点:
MockRequestFactory
在这种情况下,我不需要实例化一个类,并且仍然可以将const realRequestFactory: IRequestFactory = {
create(event: AWSLambda.APIGatewayProxyEvent): Request {
return new Request(event)
}
}
注入为类型realRequestFactory
的依赖项。这种方法似乎更简单,但是我不确定它是否会被视为最佳实践,因为它有点像单例。
是否有针对接口输入非类的共识?