2011-10-25 34 views
2

我有一個類SafeChargeDeposit繼承BaseExternalDeposit
BaseExternalDeposit在其構造函數中要求變量類型BaseDepositStructurec#設計模式 - 與基地互動

既然它需要BaseDepositStructure我不能使用它的子元素SafeChargeDeposit

這是代碼:

abstract class BaseExternalDeposit 
    { 
     public abstract BaseExternalDepositResult DoDeposit(); 

     protected BaseDepositStructure depositStructure; 

     public BaseExternalDeposit(BaseDepositStructure depositStructure) 
     { 
      this.depositStructure = depositStructure; 
     } 
    } 


class SafeChargeDeposit : BaseExternalDeposit 
{ 
     public SafeChargeDeposit(CreditCardDepositStructure depositStructure):base(depositStructure){} 

     public override BaseExternalDepositResult DoDeposit(){ 

     /////// I CAN USE THIS MEMBER: 
     depositStructure.Amount = 50; 

     /////// BUT I CANNOT USE THIS MEMBER: 
     depositStructure.CreditCardNumber = "123456"; 
     } 
} 


public class BaseDepositStructure 
    { 
     public double Amount = 0.0; 
    } 

    public class CreditCardDepositStructure : BaseDepositStructure 
    { 
     public string CreditCardNumber = string.Empty; 
    } 

我明白爲什麼我可以用depositStructure.Amount不能使用depositStructure.CreditCardNumber ... 但是,什麼是錯我的設計嗎?我該如何解決這個問題並保持使用基礎的靈活性。

回答

4
interface IBaseExternalDepositResult 
{ 
}; // eo interface BaseExternalDepositResult 

interface IDeposit 
{ 
    void Deposit(); 
}; 

// class BaseExternalDeposit<> 
abstract class BaseExternalDeposit<B> : IDeposit where B : BaseDepositStructure 
{ 
    private B depositStructure_; 
    protected abstract IBaseExternalDepositResult DepositImpl(); 
    protected B Structure { get { return depositStructure_; } } 

    public BaseExternalDeposit(B depositStructure) 
    { 
     depositStructure_ = depositStructure; 
    } // eo ctor 


    // IDeposit 
    void Deposit() 
    { 
     DepositImpl(); 
    } 
} // eo class BaseExternalDeposit<B> 


// class SafeChargeDeposit 
class SafeChargeDeposit : BaseExternalDeposit<CreditCardDepositStructure> 
{ 
    protected override IBaseExternalDepositResult DepositImpl() 
    { 
     Structure.Amount = 50; 
     Structure.CreditCardNumber = "123456"; 
    } // eo DepositImpl 


    public SafeChargeDeposit(CreditCardDepositStructure depositStructure) 
     : base(depositStructure) 
    { 
    } 
} // eo class SafeChargeDeposit 


public class BaseDepositStructure 
{ 
    public double Amount = 0.0; 
} 

public class CreditCardDepositStructure : BaseDepositStructure 
{ 
    public string CreditCardNumber = string.E 
+0

+1 + V - 這是很好的答案!謝謝 – SexyMF

+0

它確實改變了使用BaseExternalDepodsition 的可能性。在OP代碼中BaseExternalDeposit bed = new SafeChargeDeposit();是有效的howvever BaseExternalDeposit bed = new SafeChargeDeposit();將不起作用 –

+0

@RuneFS,如果需要多態性,則可以使用接口基類。我真的沒有看到這個問題。鑑於'DoDeposit()'的結果並不依賴泛型參數,這甚至可以在接口類中(如果它是公共方法所必需的)。我不相信這個答案有任何問題無法解決! :) –