2011-06-04 41 views
1

我有一個包含到> 100個000蛋對象的引用的EggSac對象。在雞蛋有些變量必須保持與EggSac一致的,所以我想使這些只有通過多變EggSac。然而EggSac傳遞給它的雞蛋引用遍佈應用程序,所以如果我使用的公共方法,然後任何其他代碼可能會意外修改雞蛋的安全部件。如何讓一些成員僅可用於一個對象?

確保只有EggSac對象可以調用Eggs的「安全」方法的正確OO方式是什麼,但仍然可以讓每個人都可以使用「安全」方法?

我的想法是雞蛋的類拆分成只包含安全的方法以及包含只EggSac應該有機會獲得安全的方法派生類的基類。然後EggSac擁有派生類類型的成員,但只要有其他需要的類,它就會將它們轉換爲其基類。

回答

0

有無EggSack保持引用EggImpl,它實現了所有必要的方法。然後繞過impl(Egg類)的包裝器,它只調用impl上的「安全」方法。

+0

神奇。乾杯。 – Slobaloba 2011-06-05 13:01:48

0

當你說的安全,你的意思是避免意外的代碼修改? 結構化的方式可以像下面這樣。 如果你想使它真的'安全',那麼你可以修改代碼來在調用類中存儲一個字符串* HashCode *,並且只有在Egg中匹配(內部調用)時,才允許修改。

Interface ISecureModifier 
{ 
    String GetSecureModifierKEY(); 
    String GetSecureModifierVALUE(); 


} 


class Egg 
{ 

    Dictionary Secure_ata; 
    public secureDataModifier(ISecureModifier modifyingObject)//note the interface being used 
    { 
     //Here, try a cast (if your compiler still allowed other type objects not implementing ISecureModifier ) and throw exception stating not authorized to modify. 
     modifyingObject.GetSecureModifierKEY 
     modifyingObject.GetSecureModifierValue 
      /*Now write the code to modify Dictionary*/ 


    } 

} 

class EggSac:ISecureModifier//implements interface 
{ 

    private string SecureModifierKEY; 
    private string SecureModifierVALUE 



    String GetSecureModifierKEY()//inteface impl 
    { 
     return SecureModifierKEY; 
    } 
    String GetSecureModifierVALUE();//interface impl 
    { 
     return SecureModifierVALUE; 
    } 

    ModifySecureData(Egg egg, string key, string value) 
    { 
     egg.secureDataModifier(this);//passing own reference 

    } 


} 

你可以叫這樣

objEggSack.ModifySecureData(objEgg101, "firstKey","NewValue") 
+0

安全,我的意思是其他代碼不能修改它。我寧願用對象而不是寫代碼來強制執行。部分原因是它看起來很醜,部分是因爲性能方面的原因 - 有時候我不得不在用戶注意到的情況下迭代這些> 100,000個雞蛋。 – Slobaloba 2011-06-08 04:36:04

相關問題