I've been studying some Object Oriented Analysis and Design lately, and I feel that I got a pretty good overall feel for it.
But this little scenario keeps bugging me.
Let's say I'm designing a simple board game. I have class Game which holds info about the board and the players. Players are created from the class Player. All players have a bank account created from the class BankAccount.
My Game handles the logic about what should happen following a move. Most of the time this involves withdrawing or depositing some amount from a players bank account.
My BankAccount has the methods for withdrawing, depositing and returning the balance. But my Game doesn't know about a players bank account. Only about the player. Do I give my Player class a method getAccount, so i can call playerObject.getAccount().withdraw()? Or how do I go about assigning the responsibility for this behaviour? Should my Player class implement a method withdraw() that just calls account.withdraw() on it's associated account object?
A
Bankought to have control of theBankAccounts, not theplayerobjects.In other words a Bank should be a collection of BankAccounts plus some additional methods for managing those accounts.
This is so you can do things like:
or
In this case the bank would "look up" the account that that player has and remove the appropriate funds from it.
Imagine if it was a real bank account. A person doesn't carry that account with them, only a reference to it. A Bank is responsible for transfer of funds (deposits, withdrawals..).
So, at a top level, you are going to have a
Gamewhich contains objects such asPlayers,Bank, andBoard. It may have top methods suchRollDice(). The Board may have a method such asMove(player, distance);