Java Reference
In-Depth Information
Strategy
For many of the collections in the Personal Information Manager, it would be useful to be able to organize and
summarize individual entries. This demonstration uses the Strategy pattern to summarize entries in a
ContactList
, a collection used to store
Contact
objects.
Example A.108
ContactList.java
1. import java.io.Serializable;
2. import java.util.ArrayList;
3. public class ContactList implements Serializable{
4. private ArrayList contacts = new ArrayList();
5. private SummarizingStrategy summarizer;
6.
7. public ArrayList getContacts(){ return contacts; }
8. public Contact [] getContactsAsArray(){ return (Contact [])(contacts. toArray(new
Contact [1])); }
9.
10. public void setSummarizer(SummarizingStrategy newSummarizer){ summarizer =
newSummarizer; }
11. public void setContacts(ArrayList newContacts){ contacts = newContacts; }
12.
13. public void addContact(Contact element){
14. if (!contacts.contains(element)){
15. contacts.add(element);
16. }
17. }
18. public void removeContact(Contact element){
19. contacts.remove(element);
20. }
21.
22. public String summarize(){
23. return summarizer.summarize(getContactsAsArray());
24. }
25.
26. public String [] makeSummarizedList(){
27. return summarizer.makeSummarizedList(getContactsAsArray());
28. }
29. }
The
ContactList
has two methods, which can be used to provide summary information for the
Contact
objects
in the collection—
summarize
and
make-SummarizedList
. Both methods delegate to a
SummarizingStrategy
,
which can be set for the
ContactList
with the
setSummarizer
method.
Example A.109
SummarizingStrategy.java
1. public interface SummarizingStrategy{
2. public static final String EOL_STRING = System.getProperty("line.separator");
3. public static final String DELIMITER = ":";
4. public static final String COMMA = ",";
5. public static final String SPACE = " ";
6.
7. public String summarize(Contact [] contactList);
8. public String [] makeSummarizedList(Contact [] contactList);
9. }
SummarizingStrategy
is an interface that defines the two delegate methods
summarize
and
makeSummarizedList
. The interface represents the Strategy in the design pattern. In this example, two classes
represent
ConcreteStrategy
objects:
NameSummarizer
and
OrganizationSummarizer
. Both classes summarize
the list of contacts; however, each provides a different set of information and groups the data differently.
The
NameSummarizer
class returns only the names of the contacts with the last name first. The class uses an inner
class as a comparator (
NameComparator
) to ensure that all of the
Contact
entries are grouped in ascending order
by both last and first name.
Example A.110
NameSummarizer.java
1. import java.text.Collator;
2. import java.util.Arrays;
3. import java.util.Comparator;
4. public class NameSummarizer implements SummarizingStrategy{
5. private Comparator comparator = new NameComparator();
6.