As you know, in many OO programming languages we can use some access modifiers to specify the access area of the fields inside the object.
for example, in java we can use public, protected or private to specify the access area for the field for all callers for this object.
but my question is that I want to specify different permissions for the called party for different callers.
the most important point: the caller class can be written by other programmers, but after my main program is written, they cannot change the resolution with their own implementation.
for example, suppose a chess game has at least 3 objects, 1 chessboard and 2 players, I want the player on the side to “read” access to all chess on the chessboard, to move “access to all black chess (and only "move" directly when he in turn), and vice versa.
I already had some ideas, as shown below, but it seems that these ideas are too complex and not ideal.
is there a good approach, design template or something else to deal with this problem?
thank you very much
// ================================================== ================
my ideas:
access key class 1.use.
- enter the class access key.
- use the game host class to assign a key instance to different players.
- A chessboard class instance has a table with key rights.
- each time the player performs the action “read” or “move” to the side, he must provide his key example as a parameter for the method, if permission is rejected, an exception is thrown.
2.use the broker management class
- inside the checkerboard there is an internal class "boardcontroller".
- 2 is a subclass of the BoardController class, 1 can move white chess, and the other can move black chess.
(although I can use some if-else in this subclass to decide that it can move some chess or not, but I want the player class to be written by another programmer and let them write their AI, so the resolution flow of judgment used by this subclass cannot be used directly in the player’s class as an approach to my question.)
- Assign the instance of the subcontroller to another player.
3.low level approach (ugly and not perfect)
in the “move” or “read” method of the board class, check the flow column to see if the caller is in the “player” class and which side (black or white).
// ================================================== =====================
any better idea? thanks