简体   繁体   中英

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. I want to make the data of this particular object be accessible by 2 objects but not the other two. 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.

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. I assumed all 5 objects were the same, if they're not thats fine too.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM