How can I make some members available to only one object?
I have an EggSac object which contains references to >100 000 Egg objects. Some variables in the Eggs have to be maintained to be consistent with EggSac, so I want to make these only changeable by EggSac. However EggSac passes references to its Eggs all over the application, so if I use public methods then any other code could modify the secure parts of the Eggs by accident.
What's a proper OO way to make sure only the EggSac object can call the "secure" methods of the Eggs, but still make the "safe" methods available to everyone?
My idea is to split Egg's class into a base class containing only safe methods and a derived class containing the secure methods that only EggSac should have access to. Then EggSac has members of the type of the derived class, but it casts them to their base class whenever开发者_开发问答 something else wants one.
Have EggSack hold references to EggImpl, which implements all the necessary methods. Then pass around wrappers over the impl (the Egg class) which only call the "safe" methods on the impl.
When you say security, do you mean avoiding accidental code modification? A structured way can be something like below. If you want to make it really 'secure', then you can modify the code to store a string*HashCode* inside the calling class and only if it's matched (inside called ) in Egg, modification is allowed.
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
}
}
You may call like this
objEggSack.ModifySecureData(objEgg101, "firstKey","NewValue")
精彩评论