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
}
}
应用:菜单。