设计模式之组合模式Composite Pattern详解Java版

一、定义

The Composite Pattern allows you to
compose objects into tree structures to
represent part-whole hierarchies. Composite
lets clients treat individual objects and
compositions of objects uniformly.
组合模式允许你组合对象到树结构中来代表部分和整体的层次结构。
组合让客户端统一对待单个对象和组合对象。

二、实例

一个公司的组织架构图如下,请使用组合模式来实现:
公司组织架构图

public abstract class Component {
	
	public void print(String head) {
		throw new UnsupportedAddressTypeException();
	}

	public void add(Component comp) {
		throw new UnsupportedAddressTypeException();
	}
	
	public void remove(Component comp) {
		throw new UnsupportedAddressTypeException();
	}
	
	public Component getChild(int i) {
		throw new UnsupportedAddressTypeException();
	}
}

class Leaf extends Component {
	private String name;
	
	public Leaf(String name) {
		this.name = name;
	}

	@Override
	public void print(String head) {
		System.out.println(head+"leaf:"+name);
	}
}

class Node extends Component {
	private String name;
	private List<Component> children;
	
	public Node(String name) {
		this.name = name;
		children=new ArrayList<>();
	}
	
	public void print(String head) {
		System.out.println(head+"node:"+name);
		head=head+"--";
		for(Component comp: children) {
			comp.print(head);
		}
	}

	public void add(Component comp) {
		children.add(comp);
	}
	
	public void remove(Component comp) {
		children.remove(comp);
	}
	
	public Component getChild(int i) {
		return children.get(i);
	}
}

测试类:

public class Test {
	public static void main(String[] args) {
		Node root=new Node("CEO");
		Leaf c1=new Leaf("财务部经理");
		Leaf c2=new Leaf("人事部经理");
		Node c3=new Node("技术部经理");
		Leaf c4=new Leaf("市场部经理");
		root.add(c1);
		root.add(c2);
		root.add(c3);
		root.add(c4);
		Node d1=new Node("部门经理");
		c3.add(d1);
		Node d2=new Node("技术主管1");
		Leaf d3=new Leaf("技术主管2");
		d1.add(d2);
		d1.add(d3);
		Leaf e1=new Leaf("软件工程师");
		Leaf e2=new Leaf("测试工程师");
		Leaf e3=new Leaf("运维工程师");
		d2.add(e1);
		d2.add(e2);
		d2.add(e3);
		
		root.print("");
	}
}

输出结果:

node:CEO
--leaf:财务部经理
--leaf:人事部经理
--node:技术部经理
----node:部门经理
------node:技术主管1
--------leaf:软件工程师
--------leaf:测试工程师
--------leaf:运维工程师
------leaf:技术主管2
--leaf:市场部经理

类图:
组合模式
分析:组合模式描述的是树状结构,叶子结点只有操作方法(其他方法调用会报错UnsupportedOperationException),而非叶子结点可以有孩子节点(可以是叶子,也可以是非叶子结点),使得客户端可以统一使用个体对象和组合对象。

三、总结

组合模式主要应用于树状结构的存储中,如公司的部门和上下级的关系,如JavaGUI的实现。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

学无止境jl

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值