Assignment 2

1. The standard OOP inheritance pattern is simple and effective but somewhat inflexible. With many classes and frequent anticipated changes a pattern like the stategy pattern becomes more appealing. Having to possibly override an inherited method for every new class added to a project would be extremely inefficient, so the Strategy pattern adds flexibility at the cost of added complexity. In Joe’s case, every modification to the base class affected every class, so he needed to make multiple changes for every new request. His idea of using an interface would have been even more inefficient, because in Java interfaces do no allow for code reuse.

This is why the strategy pattern encapsulates the parts of the program that change. In this way, code reuse and unintentional changes to other parts of the program are avoided.

2. To use the strategy pattern, take the methods from the base class that frequently need to be changed and put them in their own classes. These can be abstract classes or interfaces. Then create subclasses that implement these interfaces. The subclasses represent different ways of implementing the behavior of the interface. In my own project, the SearchBehavior interface is implemented in two different ways by predator and prey – SearchNutrients looks for inanimate food, while SearchPrey hunts animate prey.

In the base class, delegate the aforementioned behaviors to their respective interfaces. Next put setter methods in to allow easy access to the interfaces. Now any new object should be able to use the appropriate behavior by invoking its inherited setter method.