组合模式

个人博客

http://www.milovetingting.cn

组合模式

模式介绍

组合模式也称为部分整体模式,结构型设计模式之一,组合模式比较简单,它将一组相似的对象看作一个对象处理,并根据一个树状结构来组合对象,然后提供一个统一的方法去访问相应的对象,以此忽略对象与对象集合之间的差别。生活中比较经典的例子就是公司的组织结构树状图。

模式定义

将对象组合成树形结构以表示"部分-整体"的层次结构,使得用户对单个对象和组合对象的使用具有一致性。

使用场景

  1. 表示对象的部分-整体层次结构时。

  2. 从一个整体中能够独立出部分模块或功能时。

简单使用

定义节点

public abstract class Component {

	/**
	 * 节点名
	 */
	protected String name;

	public Component(String name) {
		super();
		this.name = name;
	}
	
	public abstract void doSomething();
	
	public abstract void addChild(Component child);
	
	public abstract void removeChild(Component child);
	
	public abstract Component getChild(int index);
	
}

定义枝干节点

public class Composite extends Component {

	private List<Component> components = new ArrayList<>();

	public Composite(String name) {
		super(name);
	}

	@Override
	public void doSomething() {
		System.out.println(name);
		if (components != null) {
			for (Component c : components) {
				c.doSomething();
			}
		}
	}

	@Override
	public void addChild(Component child) {
		components.add(child);
	}

	@Override
	public void removeChild(Component child) {
		components.remove(child);
	}

	@Override
	public Component getChild(int index) {
		return components.get(index);
	}

}

定义叶子节点

public class Leaf extends Component {

	public Leaf(String name) {
		super(name);
	}

	@Override
	public void doSomething() {
		System.out.println(name);
	}

	@Override
	public void addChild(Component child) {
		throw new UnsupportedOperationException("叶子节点没有子节点");
	}

	@Override
	public void removeChild(Component child) {
		throw new UnsupportedOperationException("叶子节点没有子节点");
	}

	@Override
	public Component getChild(int index) {
		throw new UnsupportedOperationException("叶子节点没有子节点");
	}

}

调用

public class Main {

	public static void main(String[] args) {
		Component root = new Composite("Root");
		
		Component branch1 = new Composite("Branch1");
		Component branch2 = new Composite("Branch2");
		
		Component leaf1 = new Leaf("Leaf1");
		Component leaf2 = new Leaf("Leaf2");
		
		branch1.addChild(leaf1);
		branch2.addChild(leaf2);
		
		root.addChild(branch1);
		root.addChild(branch2);
		
		root.doSomething();
	}

}

输出结果

Root
Branch1
Leaf1
Branch2
Leaf2
原文地址:https://www.cnblogs.com/milovetingting/p/12323875.html