The strategy pattern is one way that composition can be used as an alternative to subclassing. Rather than providing different behaviors via subclasses overriding methods in superclasses, the strategy pattern allows different behaviors to be placed in Concrete Strategy classes which share the common Strategy interface. A Context class is composed of a reference to a Strategy.
Here is an example of the strategy pattern. First, we'll define a Strategy interface. It declares a checkTemperature() method.
Strategy.java
package com.cakes; public interface Strategy { boolean checkTemperature(int temperatureInF); }The HikeStrategy class is a concrete strategy class that implements the Strategy interface. The checkTemperature method is implemented so that if the temperature is between 50 and 90, it returns true. Otherwise it returns false.
HikeStrategy.java
package com.cakes; public class HikeStrategy implements Strategy { @Override public boolean checkTemperature(int temperatureInF) { if ((temperatureInF >= 50) && (temperatureInF <= 90)) { return true; } else { return false; } } }The SkiStrategy implements the Strategy interface. If the temperature is 32 or less, the checkTemperature method returns true. Otherwise it returns false.
SkiStrategy.java
package com.cakes; public class SkiStrategy implements Strategy { @Override public boolean checkTemperature(int temperatureInF) { if (temperatureInF <= 32) { return true; } else { return false; } } }The Context class contains a temperature and a reference to a Strategy. The Strategy can be changed, resulting in different behavior that operates on the same data in the Context. The result of this can be obtained from the Context via the getResult() method.
Context.java
package com.cakes; public class Context { int temperatureInF; Strategy strategy; public Context(int temperatureInF, Strategy strategy) { this.temperatureInF = temperatureInF; this.strategy = strategy; } public void setStrategy(Strategy strategy) { this.strategy = strategy; } public int getTemperatureInF() { return temperatureInF; } public boolean getResult() { return strategy.checkTemperature(temperatureInF); } }The Demo class creates a Context object with a temperature of 60 and with a SkiStrategy. It displays the temperature from the context and whether that temperature is OK for skiing. After that, it sets the Strategy in the Context to HikeStrategy. It then displays the temperature from the context and whether that temperature is OK for hiking.
No comments:
Post a Comment