如何让一些成员只能使用一个对象?

时间:2011-06-04 15:27:00

标签: vb.net oop

我有一个EggSac对象,其中包含对> 100 000个Egg对象的引用。鸡蛋中的一些变量必须保持与EggSac一致,所以我想让这些变量只能由EggSac改变。然而,EggSac在整个应用程序中传递对其蛋的引用,因此如果我使用公共方法,那么任何其他代码都可能意外地修改了蛋的安全部分。

确保只有EggSac对象可以调用Eggs的“安全”方法,但是仍然可以为每个人提供“安全”方法,这是一种正确的OO方法吗?

我的想法是将Egg的类拆分为仅包含安全方法的基类和包含只有EggSac才能访问的安全方法的派生类。然后,EggSac具有派生类类型的成员,但只要有其他东西需要,它就会将它们转换为基类。

2 个答案:

答案 0 :(得分:0)

让EggSack保留对EggImpl的引用,它实现了所有必要的方法。然后在impl(Egg类)上传递包装器,它只调用impl上的“安全”方法。

答案 1 :(得分: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")