Java Reference
In-Depth Information
Listing 2.11
The OfferAggregator class
package fancyfoods.offers.impl;
import java.util.*;
import fancyfoods.offers.CurrentOffers;
import fancyfoods.offers.SpecialOffer;
public class OfferAggregator implements CurrentOffers {
private static final int MAX_OFFERS = 4;
private List<SpecialOffer> offers;
List of offers
gets injected
public void setOffers(List<SpecialOffer> offers) {
this.offers = offers;
Format offers
into a table
public List<SpecialOffer> getCurrentOffers() {
List<SpecialOffer> sortedOffers =
new ArrayList<SpecialOffer>(offers);
Collections.sort(sortedOffers, new OfferComparator());
int offerCount = Math.min(MAX_OFFERS, sortedOffers.size());
return sortedOffers.subList(0, offerCount);
Sort offers
by price
Trim list
private static class OfferComparator implements
Comparator<SpecialOffer> {
public int compare(SpecialOffer offer1, SpecialOffer offer2) {
return ((Double) offer2.getOfferFood().getPrice()).
If you want to liven things up and make the OfferAggregator work a bit harder, you
can register more SpecialOffer implementations. They will all magically appear in
the list passed to the OfferAggregator . Figure 2.14 shows how the application archi-
tecture would look with an extra cheese department.
The offer aggregator applies the Fancy Foods business logic to the raw list of cur-
rent offers. Flooding customers with a big long list of promotions will only confuse
them, so the aggregator restricts the offer count to four. Customers will probably get
more excited by offers for high-cost items, so the aggregator puts those at the top of
the list.
References and reference lists
The offer aggregator assumed that multiple offers would be registered, and present-
ing a list of offers was the right thing to do. For some other types of service, only one is
ever required. For example, it would be quite wrong to process credit card payments
more than once just because multiple credit card payment processing providers were
available! If you only want one implementation, use a <reference> element instead of
a <reference-list> . If multiple services are available, the container will supply one
Search WWH ::

Custom Search