Composite Pattern 组合模式

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.

This pattern gives us a way to create a tree structure that can handle a nested group of menus and menu items in the same structure. The composite pattern allows us to build structures of objects in the form of trees that contain bot compositions of objects and individual objects as nodes. Using a composite structure, we can apply the same operations over both composites and individual objects. In other words, in most cases we can ignore the differences between compositions of objects and individual objects.

组合模式有时又叫做部分-整体模式(Part-Whole)。组合模式将对象组织到树结构中,可以用来描述整体与部分的关系。组合模式可以使客户端将单纯元素与复合元素同等看待。

定义Component抽象类:

public abstract class Component {
	public void add(Component component) {
		throw new UnsupportedOperationException();
	}
	public void remove(Component component) {
		throw new UnsupportedOperationException();
	}
	public void operation() {
		throw new UnsupportedOperationException();
	}
	public void getChild(int pos) {
		throw new UnsupportedOperationException();
	}
}
方法的默认值为Exception

定义Leaf(单纯元素):

public class Leaf extends Component {
	@Override
	public void operation() {
		// do something
	}
}
定义Composite(复合元素):

public class Composite extends Component {
	@Override
	public void add(Component component) {
		// do something
	}
	@Override 
	public void remove(Component component) {
		// do something
	}
	@Override
	public void operation() {
		// do something
	}
	@Override
	public void getChild(int pos) {
		// do something
	}
}

应用:菜单。


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值