关闭

Composite Pattern 组合模式

231人阅读 评论(0) 收藏 举报
分类:

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

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:69666次
    • 积分:2064
    • 等级:
    • 排名:第19178名
    • 原创:145篇
    • 转载:0篇
    • 译文:0篇
    • 评论:1条
    最新评论