Design Patterns Java™ Workbook

(Michael S) #1
Chapter 23. Strategy

String promotedFireworkName =
p.getProperty("promote");
if (promotedFireworkName != null)
{
promoted = Firework.lookup(
promotedFireworkName);
}
}
catch (Exception e)
{
}
}


public boolean hasItem() {
return promoted != null;
}


public Firework recommend(Customer c) {
return promoted;
}
}


The RandomAdvisor class is simple:


package com.oozinoz.recommend;
import com.oozinoz.fireworks.*;
public class RandomAdvisor implements Advisor
{
public static final RandomAdvisor singleton =
new RandomAdvisor();


private RandomAdvisor()
{
}


public Firework recommend(Customer c)
{
return Firework.getRandom();
}
}


CHALLENGE 23.3


Write the code for ItemAdvisor.java.

The refactoring of Customer separates the selection of a strategy (or "advisor") from the use
of the strategy. An advisor attribute of a Customer object holds the context, or current
choice, of the strategy to apply. The refactored Customer class lazy-initializes this attribute
with logic that reflects Oozinoz's advertising policies:

Free download pdf