vendredi 1 janvier 2016

a design pattern or approach to handle access control of the fields of an object

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 wrote 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.

  • make an class "access key".
  • use a "game hoster" class to assign "key" instance to different players.
  • the chessboard class instance has a key-right map table.
  • each time the player do the "read" or "move" action toward the board,it must give their key instance as a parameter to the method, if the permission is denied ,exception thrown .

2.use mediate controller class

  • there are an inner class "boardcontroller" inside the chessboard.
  • 2 sub-class of boardcontroller,1 can move the white chess,the other for black chess.

(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 wrote by other programer,and let them write their AI,so the permission judgement flow can not be used directly inside the player class)

  • assign the sub-boardcontroller instance to different player.

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

Aucun commentaire:

Enregistrer un commentaire