Java设计模式-----Composite模式

源自:http://www.blogjava.net/flustar/archive/2007/12/18/composite.html

Composite模式:

将对象组合成树形结构以表示“整体—部分”的层次结构。Composite模式使单个对象和组合对象的使用具有一致性。

例子:

public abstract class MovieClass {
	
	public String name;
	public ArrayList
   list;

	public abstract void add(MovieClass component);

	public abstract void remove(MovieClass component);

	public abstract void display();
}

public class Program extends MovieClass {

	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");
	}
}

public class ConcreteMovieClass extends MovieClass {

	public ConcreteMovieClass(String name) {
		this.name = name;
		list = new ArrayList
  ();
	}

	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 Client {
	
	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();// 显示节目列表
	}
}

你可能感兴趣的:(java,设计模式,String,object,Class,影视)