Java Reference
In-Depth Information
public ExpenseProductCountCalculator(String productToFind) {
this.product = productToFind;
}
@Override
protected void initialize() {
count = 0;
}
@Override
protected void handle(Expense expense) {
if (expense.getProduct().equals(product))
count++;
}
@Override
protected double getResult() {
return count;
}
}
The benefit of using this pattern comes not only from the fact that you can now easily create new
implementations for a general algorithm, but you will also able to work with all these algorithms
in a general manner, using the abstract class. You could now, for instance, easily define a list of
ExpenseListCalculator objects that should be executed one by one and added to a report.
Strategy Pattern
The strategy pattern also deals with generalizing algorithms, but here, the focus is on selecting a
particular algorithm at runtime, instead of algorithms extending a general template.
To see how this works, let's say you have a customer class. You want to add a method in order to
send notification messages to this user. Depending on the user's preferences, they can be notified by
text message, email, or Twitter. You want to avoid adding a bunch of notifySMS , notifyEmail , and
notifyTwitter methods, which look ugly and are hard to maintain later on. There should be a bet-
ter, object‐oriented way to do this.
You realize that all these ways of notifying a customer can be regarded as different notification
strategies, and thus get to work. First, you define a general interface:
public interface NotifyStrategy {
public void notify(Customer customer, String message);
}
The customer class looks something like this:
public class Customer {
private NotifyStrategy notificationPreference;
public Customer(NotifyStrategy notificationPreference) {
this.notificationPreference = notificationPreference;
}
 
Search WWH ::




Custom Search