as we know,in many OO program language ,we can use some access modifiers to specify the access scope of the fields inside an object .
for example, in java we can use public,protected or private to specify the access scope of a field ,for all of the caller to this object .
but my question is that ,I want to specify different access permissions of a callee , for different callers.
the most important point is: the caller class could be written by other programmers, but after my main program is written, they can not change the permission by their own implementation.
for example ,suppose there are at least 3 entities in the chess game program, 1 chessboard and 2 players , I want let the Black side player have "read" access right to all of the chess on the chessboard,but just "move" access access right to all of the black chess,(and only have "move" right when it's in his turn) , and vice versa .
I have already had some ideas as below,but It seems that these ideas are too complicated and not ideal.
so is there any good approach、design pattern,or something else to deal with this problem ?
many thanks
//===============================================================
my ideas:
1.use access key class.
2.use mediate controller class
(although I can use some if-else in this sub-class to decide it can move some chess or not ,but I want let the player class be written by other programer,and let them write their AI,so the permission judgement flow used by these sub-class can not be used directly in the player class as a approach for my question.)
3.low level approach(ugly and not ideal)
in "move" or "read" method of the board class,check the callstack of the thread ,to know is the caller belong to the class "player", and which side(black or white) it is.
//===================================================================
any better idea? thank you
Proxy is what you need.
This design pattern is controlling access to a specific object, can control their creation or anything.
Best part about it is that client has no idea that he is using a proxy. Only part is if client calls method that it has no access of you can throw some exception. In this case you have to modify class interface for each such method to be throwing exception, actual implementation wont do it, but for the sake of proxy this is good solution.