我的情况类似于下面的情况:
interface IAbstractPaymentService { void ProcessPayment(); }
interface IPaymentGateway1Service : IAbstractPaymentService { } // Do not define extra methods but needed for IoC container configuration
interface IPaymentGateway2Service : IAbstractPaymentService { } // Do not define extra methods but needed for IoC container configuration
public abstract class PaymentProcessor
{
protected abstract void ThisMethodNeedsASpecializedService(IAbstractPaymentService abstractPaymentService);
}
public class PaymentGateway1Processor : PaymentProcessor
{
protected override void ThisMethodNeedsASpecializedService(IAbstractPaymentService abstractPaymentService)
{
return ThisMethodNeedsASpecializedService(abstractPaymentService as IPaymentGateway1Service) // Don't worry, I do security checks
}
public void ThisMethodNeedsASpecializedService(IPaymentGateway1Service paymentGateway1Service)
{
paymentGateway1Service.ProcessPayment();
}
}
public class PaymentGateway2Processor : PaymentProcessor
{
protected override void ThisMethodNeedsASpecializedService(IAbstractPaymentService abstractPaymentService)
{
return ThisMethodNeedsASpecializedService(abstractPaymentService as IPaymentGateway2Service) // Don't worry, I do security checks
}
public void ThisMethodNeedsASpecializedService(IPaymentGateway2Service paymentGateway2Service)
{
paymentGateway2Service.ProcessPayment();
}
}
我对这种抽象并不满意,因为多态的想法是你不关心底层类型,你只想要应用某种行为。但是在这里,即使我创建了PaymentProcessor的工厂,每次消费者需要调用ThisMethodNeedsASpecializedService()时,他都需要知道底层类型以注入正确的服务。
我在考虑将服务存储在内部属性中,这样我就可以创建一个在创建时注入服务的工厂,而消费者不需要知道所使用的服务 - 因此,不会关心基础类型。但我总是看到将一个服务实例存储在一个属性中的事实是一种不好的做法,并且不确定我是否应该这样做。
你怎么看待它,你会以不同的方式做到吗?
答案 0 :(得分:0)
实现结构的更好方法是通过IAbstractPaymentService
构造函数注入PaymentProcessor
。例如:
public abstract class PaymentProcessor
{
protected abstract void ThisMethodNeedsASpecializedService();
}
public class PaymentGateway1Processor : PaymentProcessor
{
private IPaymentGateway1Service paymentGateway1Service;
public PaymentGateway1Processor(IPaymentGateway1Service paymentGateway1Service){
this.paymentGateway1Service = paymentGateway1Service;
}
public void ThisMethodNeedsASpecializedService()
{
this.paymentGateway1Service.ProcessPayment();
}
}