When implementing the Strategy Pattern, where does one put the code that determines which strategy to use? Some sample pseudo-code would help.
When implementing the Strategy Pattern, where does one put the code that determines which
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
That decision is taken by the client of the Objects that use the Strategy Pattern. Lets say for instance that you have a Character Object that attacks other characters using a different attack style based on which Weapon the Character posesses at the time. The decision of which Strategy to use would then be made by the player of the game when she chooses which weapon the character will use.
So neither the Character nor the Weapon (the two main components of the Strategy Pattern in the example) decides which Strategy to use, rather the code that makes use of Characters and Weapons do so. By simply creating a new Weapon object (say a RayGunWeapon) and “giving” it to your Character changes the Character’s behaviour.
Even though you could write code that explicitly chooses a Strategy, I think the real value of this pattern is that it can be done at run time.