设计模式-组合模式

组合模式思维导图
组合模式思维导图

设计模式-组合模式
1、定义

将对象组合成树形结构以表示“部分-整体”的层次结构,使得用户对单个对象的使用具有一致性。(一个对象包含其他对象的引用,称这样的对象为组合对象。)

2、分类

分类:结构型模式

3、优点

优点:
用户可方便处理个体对象和组合对象;
组合对象和个体对象实现了相同的接口,用户一般无需区分个体对象和组合对象;
当增加新的 Component 节点和 Leaf 节点时,用户的重要代码不需要做修改,更容易添加新类型的组件。

4、适用场景

想表示对象的部分-整体层次结构;
希望用户用一致的方式处理个体对象和组合对象。

5、UML类图

组合模式UML类图
角色:
Component 抽象组件:定义了叶子节点和容器构件的共同点;
Composite 节点:有容器特征,可以包含子节点;
Leaf 节点:没有子节点。

6、代码实现
import java.util.ArrayList;

//step1. 抽象组件 Component
interface Component {
	public void add(Component component);
	public void remove(Component component);
	public Component getChild(int index);
	public abstract void operation();
}
//step2. Composite 节点
class Composite implements Component {
	private ArrayList<Component> list = new ArrayList<Component>();
	public void add(Component c) {
		if(!(list.contains(c)))
			list.add(c);
	}
	public void remove(Component c) {
		if(list.contains(c))
			list.remove(c);
	}
	public Component getChild(int i) {
		if(i>=0&i<list.size())
			return (Component) list.get(i);
		return null;
	}
	public void operation() {
		System.out.println("Composite Node");
		for(Component c:list)
			c.operation();
	}
}
//step3. Leaf 节点
class Leaf implements Component {
	public void add(Component component) {
		System.err.println("Don't support add");
	}
	public void remove(Component component) {
		throw new UnsupportedOperationException("对象不支持此功能");
	}
	public Component getChild(int index) {
		return null;
	}
	public void operation() {
		System.out.println("Leaf Node");
	}
}
//step4. Demo
public class TestAwen {
	public static void main(String[] args) {
		Composite root = new Composite();
		Component c1 = new Composite();
		Component c2 = new Composite();
		Component leaf1 = new Leaf();
		Component leaf2 = new Leaf();
		Component leaf3 = new Leaf();
		root.add(c1);
		root.add(c2);
		root.add(leaf1);
		c1.add(leaf2);
		c2.add(leaf3);
		root.operation();
	}
}

运行结果截图
组合模式运行结果截图

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值