设计模式之组合(composite)

阅读更多

将对象组合成树形结构以表示“部分与整体”的层次结构。

 

public class CompositePattern {
	
	abstract class Component{
		abstract void add(Component c);
		abstract void remove(Component c);
		abstract void display();
	}
	
	class Leaf extends Component{
		private String Content;
		public Leaf(String content){
			this.Content = content;
		}
		
		@Override
		void add(Component c) {
		}
		@Override
		void display() {
			  System.out.println(this.Content);
		}
		@Override
		void remove(Component c) {
		}
	}
	
	class Composite extends Component{
		private List list = new ArrayList();
		
		public Composite(){
			
		}
			
		@Override
		void add(Component c) {
			list.add(c);
		}

		@Override
		void display() {
			for(Component c : list){
				c.display();
			}
		}

		@Override
		void remove(Component c) {
			if(list.contains(c)){
				list.remove(c);
			}
		}
	}
	public static void main(String[] args){
		CompositePattern cp = new CompositePattern();
		Component c2 = cp.new Composite();
		Component leaf21 = cp.new Leaf("leaf21");
		Component leaf22 = cp.new Leaf("leaf22");
		c2.add(leaf21);
		c2.add(leaf22);
		
		Component c23 = cp.new Composite();
		Component leaf231 = cp.new Leaf("leaf231");
		Component leaf232 = cp.new Leaf("leaf232");
		c23.add(leaf231);
		c23.add(leaf232);
		//对单个对象leaf与组整体对象composite在使用上具有一至性
		c2.add(c23);
		//递归输出
		c2.display();
	}
}

你可能感兴趣的:(composite,组合模式)