The Composite Pattern
An Introduction with Examples in Java |
Prof. David Bernstein |
Computer Science Department |
bernstdh@jmu.edu |
In UML:
A Message Distribution System
/** * Requirements of a Distribution (i.e., where a message * can be sent) in a distribution system. * * @author Prof. David Bernstein, James Madison University * @version 1.0 */ public interface Distribution { /** * Send a message. * * @param msg The message to send */ public void sendMessage(String msg); }
import java.util.*; /** * An encapsulation of a DistributionList. * * @author Prof. David Bernstein, James Madison University * @version 1.0 */ public class DistributionList implements Distribution { private Collection<Distribution> aggregate; /** * Default Constructor */ public DistributionList() { aggregate = new HashSet<Distribution>(); } /** * Add a Distribution to this DistributionList * * @param d The Distribution to add */ public void add(Distribution d) { aggregate.add(d); } /** * Send a message to this DistributionList * (required by Distribution) * * @param out The PrintStream to print on */ public void sendMessage(String msg) { for (Distribution d: aggregate) { d.sendMessage(msg); } } /** * Remove a Distribution from this DistributionList * * @param d The Distribution to remove */ public void remove(Distribution d) { aggregate.remove(d); } }
/** * An example of the Composite Pattern * * @author Prof. David Bernstein, James Madison University * @version 1.0 */ public class Driver { /** * The entry-point of the application * * @param args The command-line arguments */ public static void main(String[] args) { DistributionList cs, math, spam; EmailAddress dean; spam = new DistributionList(); dean = new EmailAddress("Tex Avery", "tex@hollywood.edu"); cs = new DistributionList(); cs.add(new EmailAddress("Gilligan", "littlebuddy@island.edu")); cs.add(new EmailAddress("The Skipper", "skipper@island.edu")); cs.add(new EmailAddress("Mr. and Mrs. Howell", "magoo@island.edu")); math = new DistributionList(); math.add(new EmailAddress("Fred Flintstone", "bedrock.edu")); math.add(new EmailAddress("Barney Rubble", "bedrock.edu")); math.add(new EmailAddress("Stony Curtis", "hollyrock.edu")); spam.add(cs); spam.add(math); spam.add(dean); spam.sendMessage("Buy my book!"); } }