组合(Composite)模式,又可以叫部分-整体模式。也是属于结构型设计模式之一,这个设计模式相对adapter和decorator来说比较容易理解些。composite模式适合用于构造树型的数据结构,例如,用于实现操作系统的目录,目录中可以包含节点(子目录)和叶子节点(文件)。从网上摘了一个例子,如下:
- package composite;
- import java.util.ArrayList;
- abstract class MovieClass{//Component
- public String name;
- public ArrayList<MovieClass> list;
- public abstract void add(MovieClass component);
- public abstract void remove(MovieClass component);
- public abstract void display();
- }
- class Program extends MovieClass{//Leaf
- public Program(String name){
- this.name=name;
- }
- public void add(MovieClass component){
- System.out.println("you can't add component to a proagram object");
- }
- public void display() {
- System.out.println("----------"+name);
- }
- public void remove(MovieClass component) {
- System.out.println("you can't remove component to a proagram object");
- }
- }
- class ConcreteMovieClass extends MovieClass{//Composite
- public ConcreteMovieClass(String name){
- this.name=name;
- list=new ArrayList<MovieClass>();
- }
- public void add(MovieClass component) {
- list.add(component);
- }
- public void remove(MovieClass component) {
- if(list.contains(component)){
- list.remove(component);
- }
- }
- public void display(){
- System.out.println(name);
- for(MovieClass mc:list){
- mc.display();
- }
- }
- }
- public class Test {
- public static void main(String args[]){
- Program pro=new Program("大汉天子");
- Program pro2=new Program("贞观长歌");
- ConcreteMovieClass cmc=new ConcreteMovieClass("电视连续剧");//一级分类
- cmc.add(pro);
- cmc.add(pro2);
- Program pro3=new Program("满城尽带黄金甲");
- Program pro4=new Program("色戒");
- ConcreteMovieClass cmc2=new ConcreteMovieClass("最新影视");//一级分类
- cmc2.add(pro3);
- cmc2.add(pro4);
- Program pro5=new Program("越狱");
- Program pro6=new Program("英雄");
- ConcreteMovieClass secondCmc=new ConcreteMovieClass("热播美剧");//二级分类
- secondCmc.add(pro5);
- secondCmc.add(pro6);
- cmc2.add(secondCmc);//在一级分类(最新影视)下添加二级分类热播美剧
- ConcreteMovieClass root=new ConcreteMovieClass("root");
- root.add(cmc);
- root.add(cmc2);
- root.display();//显示节目列表
- }
- }
在组合模式中,抽象类或者接口必须要定义对组件操作相关的方法,节点和叶子节点都必须继承或者实现抽象类或者接口。
tomcat中的container接口的设计就使用了组合模式,engin根节点中可以包含多个host,host节点又可以包含多个context,context节点中可以包含多个叶子节点wraper。
参考资料:http://blog.csdn.net/vincentzhao2009/article/details/6201724