[英]Suppose I have 5 objects. I want the data of this particular object be accessible by 2 objects but not the other two. How can I do that?
Suppose I have 5 objects.假设我有 5 个对象。 I want to make the data of this particular object be accessible by 2 objects but not the other two.
我想让这个特定对象的数据可以被 2 个对象访问,但不能被其他两个对象访问。 How can I do that?
我怎样才能做到这一点?
Very generic question!很笼统的问题! In java, I might suggest that you set up the packaging such that the package of the data supplier and intended allowed data consumers was the same, and the data supplier's methods are defined as "protected", and the non-privileged two classes are in a separate package.
在java中,我可能会建议你设置打包,使得数据提供者和预期允许的数据消费者的包是相同的,并且数据提供者的方法被定义为“受保护”,非特权的两个类在一个单独的包。
But that's only one of about a million ways you might approach such a general question.但这只是您处理这样一个普遍问题的大约一百万种方法中的一种。
A dead simple approach: set a boolean within each class.一个非常简单的方法:在每个类中设置一个布尔值。
public class MyObject{
boolean hasPermission;
Data myData;
public Data getData(boolean permission){
if(permission)
return myData;
else
return null;
}
}
Whenever you create the objects...每当您创建对象时...
MyObject hasData = new MyObject();
MyObject iHaveAccess = new MyObject();
MyObject iHaveAccess2 = new MyObject();
MyObject iDontHaveAccess = new MyObject();
MyObject iDontHaveAccess2 = new MyObject();
iHaveAccess.hasPermission = true;
iHaveAccess2.hasPermission = true;
iDontHaveAccess.hasPermission = false;
iDontHaveAccess2.hasPermission = false;
When you want to get the data当你想获取数据时
hasData.getData(iHaveAccess.hasPermission); // returns data
hasData.getData(iDontHaveAccess.hasPermission); // returns null
Obviously, don't implement it literally as i did, do it with loops.显然,不要像我一样从字面上实现它,用循环来实现。 You can also set the
hasPermission
boolean in the constructor.您还可以在构造函数中设置
hasPermission
布尔值。 I assumed all 5 objects were the same, if they're not thats fine too.我假设所有 5 个对象都是相同的,如果它们也不是很好。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.