The pattern Strategy (Strategy) defines a family of algorithms, encapsulates and makes interchangeable. Allowing each algorithm vary independently of the clients who use it.
It is used to encapsulate those parts of the code that range, making these changes do not affect the rest of the code, thus avoiding unintended consequences to our code and providing greater flexibility.
To illustrate with an example, suppose you have a group of terminals which have their own method of entry and exit data, eg. keyboard, monitor, mouse, and so on.
Suppose that in this moment we only have 3 methods of entry and exit 2, but we know that in the future are going to add more, why use the Strategy Pattern to encapsulate the methods of entry and exit, allowing the future implementation of the new terminal with great ease and without affecting the existing ones.
To encapsulate the methods of entry will resort to the use of interfaces , create an input and an output interface, which will be implemented by each method of input / output data. In turn, we need several Terminals and can add new types to use this inheritance, all our terminals will inherit the superclass Terminal.
The terminal will have a class instance variable of type Entry (interface) and an output of type (interface).
Besides creating a class for each method of entry and exit which will implement the appropriate interface. We may also define a class, for example Monitor_TouchScreen that implements both interfaces, so you can use it as a method of entry and exit.
In the diagrams we see the input and output interfaces with the classes that implement, and the superclass Terminal with their subclasses.
Now we can go one step further and create a Terminal mutable, (what name, not by that name ?), I refer to a terminal that can change their method of entry and / or output at runtime This sounds much more complex than it really is, because the only difference between the terminals that we have created thus far is that this will have to define a setter for the input method and a method for the departure, while the rest remains unchanged .
Códijo You can download the source of this implementation in Java by clicking here. To run you have to go to the directory bin / and run
Also, you may be interested: