jeudi 27 octobre 2016

Is there someway to restrict the access to a member of an object only to the object that owns it by composition?

I really feel like there must be a way around this.

Imagine I have a large number of objects as components of an owner class. I want to offer easy access to the clients of this owner class to its members, so I make all those objects public. Each of those objects also have all their members public. But one member of the components should not be accessible to the clients of their owner, only by their owner itself:

public class ComponentObject
{
    public int int_field;
    public float float_field;
    public Object object_field;

    public Object public_method1()
    {
        //something;
    }

    public Object public_method2()
    {
        //something;
    }

    public Object restricted_to_owner_only()
    {
        //something;
    }
}

//all clients of Owner should be able to access all the members of its components, except
//restricted_to_owner_only, which only Owner should be able to access
public class Owner
{
    public ComponentObject component1;
    public ComponentObject component2;
    public ComponentObject component3;
    //... lots of others
    public ComponentObject component300;
}

Is there a way to achieve this? Note that any class from any package can own a ComponentObject, so using package level visibility at restricted_to_owner_only doesn't seem to be an option. ComponentObject is like a utility class, reusable in other applications.

Aucun commentaire:

Enregistrer un commentaire