我真的觉得必须有办法解决这个问题。
想象一下,我有大量对象作为所有者类的组件。我想为其成员提供对该所有者类的客户的轻松访问,因此我将所有这些对象公开。这些对象中的每一个也都有其所有成员公开。但是组件的一个成员不应被其所有者的客户访问,只能由其所有者自己访问:
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;
}
有没有办法做到这一点?请注意,任何包中的任何类都可以拥有 a ComponentObject
,因此使用包级别的可见性 atrestricted_to_owner_only
似乎不是一种选择。ComponentObject
就像一个实用程序类,可在其他应用程序中重用。
也许有一个注释可以在编译时在一些不错的库中强制执行?
编辑:我忘了提到 ComponentObject 是现实生活中的参数化类型,并且 Owner 中的每个字段都以不同的方式参数化。我试图抽象出细节,以便我们可以专注于设计问题本身,但我抽象的太多了。我将在下面发布与实际问题更相似的内容:
public class ComponentObject<T>
{
public int int_field;
public float float_field;
public T object_field;
//any method could return T or take T as an argument.
public T 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<String> component1;
public ComponentObject<File> component2;
public ComponentObject<Consumer<Boolean>> component3;
//... lots of others
public ComponentObject<Integer> component300;
}
编辑2(可能是一个解决方案):伙计们,受罗密欧与朱丽叶的爱情启发,我写了这个解决方案,你能发现它有什么问题吗?或者它会按我的意愿工作吗?
//add this class
public class OwnershipToken
{
private static int id_gen = 0;
public final int id = id_gen++;
@Override
public boolean equals(Object obj)
{
return (obj instanceof OwnershipToken) && ((OwnershipToken)obj).id == id;
}
@Override
public int hashCode()
{
return id;
}
}
//Then change this in ComponentObject<T>:
public class ComponentObject<T>
{
//add this field:
private final OwnershipToken ownershipToken;
//add this constructor
public ComponentObject(OwnershipToken onwershipToken)
{
this.ownershipToken = ownershipToken;
}
//change restricted_to_owner_only signature:
public Object restricted_to_owner_only(OwnershipToken ownershipToken)
{
//add this condition
if(this.ownershipToken.equals(ownershipToken)
//something;
}
}
//finally, Owner gains a field:
public class Owner
{
private final OwnershipToken ownershipToken = new OwnershipToken();
//... etc, remainder of the class
}
这会按预期工作吗?