2015-02-24 75 views
1

我有類似下面的一個情況:設計點:是多態性合適我的情況

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

更好的方法來阻止你的結構是通過PaymentProcessor costructor注入IAbstractPaymentService。例如:

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(); 
    } 
} 
+0

這就是我最後做的,所以你投了票:將服務存儲在內部屬性中。我也意識到,在這種情況下,這不應該是一個壞習慣。感謝您的洞察力 – reddy 2015-02-24 14:53:17