Number of questions 1,751
Number of tests completed 252,495
Number of questions answered 3,765,643
Number of registered users 19,174
Sign In | Register
Skip Navigation Links
Question: Match this design pattern: Encapsulates an algorithm inside a class
Answer1: Singleton
Answer2: Strategy
Answer3: Adapter
Answer4: Decorator
Answer5: State
Answer: Strategy

Explaination: The strategy pattern is used to solve problems that might (or is foreseen they might) be implemented or solved by different strategies and that posses a clearly defined interface for such cases, being ecah strategy perfectly valid in is own with some of them being preferable on some situations allowing the application to switch between them on runtime. You have a class Car() with a method run() so you use it this way in a pseudo language : mycar = new Car() Now, you may want to change the run() behavior on the fly, while the program is executing. E.G : to simulate a motor failure or the use of a "boost" button in a video game. There are several ways to do that : using conditional statements and a flag variable is one of them. The strategy pattern is another, that delegate the behaviour of the run() method to a subclass : Class Car() { this.motor = new Motor(this) // passing "this" is important for the motor so it knows what it is running method run() { } method changeMotor(motor) { this.motor=motor } } If you want to change the car behavior, you can just change the motor (easier in a program that in the real life, right ;-) ?) It's very useful if you have a lot of complex states : you can change and maintain them much more easily.
Link: External Explaination

Correctly answered: 2553
Incorrectly answered: 3125
Terms of Use Ver. 2.0.6783.38332