场景
MM拉着我去逛街,给她买一件衣服,结果到了商场,这个衣服也喜欢,那个裤子也喜欢,那个包包也不错;为了表现出不慷慨大方绅士之举,买买买!都买下,正好凑成一套.
意图
1.将对象组合成树形结构以表示”部分一整体”的层次结构。
2.组合模式使得用户对单个对象和组合对象的使用具有一致性。
3.屏蔽了容器对象与单个对象在使用时的差异,为客户端提供统一的操作接口,
从而降低客户代码与被调用对象的耦合关系,方便系统的维护与扩展.
使用场合
1.你想表示对象的部分-整体层次结构
2.你希望用户忽略组合对象与单个对象的不同,用户将统一地使用组合结构中的所有对象。
UML图
Component 是组合中的对象声明抽象类(也可以定义成接口,具体类),在适当的情况下,实现所有类共有的默认行为。声明一个抽象类用于访问和管理Component
public abstract class Component {
public void operation() {
System.out.println("Component");
}
}
子部件Leaf 在组合中表示叶子结点对象,叶子结点没有子结点。
public class Leaf extends Component {
public void operation() {
System.out.println("Leaf");
}
}
子节点Composite 定义有枝节点行为,用来存储子部件,在Component接口中实现与子部件有关操作,如增加(add)和删除(remove)等。
public class Composite extends Component {
private List<Component> components = new ArrayList();
public void operation() {
for (Component component : components) {
component.operation();
}
}
// Adds the component to the Composite.
public void add(Component component) {
components.add(component);
}
// Removes the component from the Composite.
public void remove(Component component) {
components.remove(component);
}
}
组合模式构建完毕!接下来我们写个测试类:
public class ClientComposite {
public static void main(String[] args) {
//Initialize three blocks
Leaf leaf1 = new Leaf();
Leaf leaf2 = new Leaf();
Leaf leaf3 = new Leaf();
//Initialize three structure
Composite composite1 = new Composite();
Composite composite2 = new Composite();
Composite composite3 = new Composite();
//Composes the groups
composite1.add(leaf1);
composite2.add(leaf2);
composite3.add(leaf3);
composite1.add(composite2);
composite1.add(composite3);
composite1.operation();
}
}
输出结果为:
Leaf
Leaf
Leaf
优点
1.组合模式定义了包含基本对象和组合对象的类层次结构。
2.基本对象可以被组合成更复杂的组合对象,而这个组合对象又可以被组合,这样不断地递归下去,客户代码中,任何用到基本对象的地方都可以使用组合对象了。
3.用户不用关心到底是处理一个叶节点还是处理一个组合组件,也就是用不着为定义组合而写一些选择判断语句了,简单地说就是组合模式让客户可以一致地使用组合结构和单个对象。
MM引领去逛街,对每件衣服、每条裤子、每个包包都爱不释手,为了表现绅士风范,毅然决然买下全部商品,形成一套完整的搭配。组合模式在此场景下完美应用,实现部分与整体的层次结构,提升用户体验,简化代码复杂度。

398

被折叠的 条评论
为什么被折叠?



