设计模式专题之组合模式讲解

定义(百度百科):将对象组合成树形结构以表示“部分整体”的层次结构。组合模式使得用户对单个对象和组合对象的使用具有一致性。

UML类图:

具体代码:

public class Client {public static void main(String[] args) throws UnmarshalException {        Component root = new Composite();        Component c1 = new Composite();        Component c2 = new Composite();        Component leaf1 = new Leaf();        Component leaf2 = new Leaf();        Component leaf3 = new Leaf();        root.add(c1);        root.add(c2);        root.add(leaf1);        root.add(leaf2);        root.add(leaf3);        Component o = root.get(0);        o.operation();        Component o1 = root.get(1);        o1.operation();        Component o2 = root.get(2);        o2.operation();    }}public abstract class Component {abstract void operation();void add(Component c) throws UnmarshalException {         throw new UnmarshalException("不支持");    }void remove(Component c) throws UnmarshalException {throw new UnmarshalException("不支持");    }    Component get(int index) throws UnmarshalException {throw new UnmarshalException("不支持");    }}public class Composite extends Component {    List<Component> list = null;    @Overridevoid operation() {        System.out.println("Composite");         if (!CollectionUtil.isEmpty(list)) {             for (Component c : list) {                c.operation();             }         }    }    @Overridevoid add(Component c) throws UnmarshalException {if (CollectionUtil.isEmpty(list)) {            list = new ArrayList<>();        }        list.add(c);    }    @Overridevoid remove(Component c) throws UnmarshalException {if (!CollectionUtil.isEmpty(list)) {             list.remove(c);        }    }    @Override    Component get(int index) throws UnmarshalException {if (!CollectionUtil.isEmpty(list)) {             return list.get(index);        }return null;    }}public class Leaf extends Component {    @Overridevoid operation() {        System.out.println("叶子节点操作");    }}

模块说明:

Component(抽象构件):Component是组合中的对象声明抽象类,在适当的情况下,实现所有类共有接口的默认行为。用于访问和管理Component子部件。Composite(容器构件):定义有枝节点行为,用来存储子部件,在Component接口中实现与子部件有关操作,如增加(add)和删除(remove)等Leaf(叶子构件):Leaf 在组合中表示叶子结点对象,叶子结点没有子结点

具体例子:

举个新闻客户端的例子,菜单分类,部门机构的分类,公司部门的分类等等。

应用场景:描述树形结构,可以统一操作树的全部节点,增加删除获取等等。

优缺点:优点:包含了基础对象和组合对象的层次结构简化了客户端的调用,对组合还是子叶不用区分对待。可以增加子叶,增加了扩展性。

缺点:安全性和透明性是个不可调和的矛盾。当然此模式实现更多考虑透明性,对子叶还是组件一视同仁,这样相对子叶和组合对象分别处理变得十分困难,需要做类型转换,这显然影响安全性。另外当业务越来越复杂,对组件抽象也是很大的挑战。

总结:统一了子叶和组合对象的操作。

以上就是设计模式专题之组合模式讲解的详细内容,更多请关注其它相关文章!

真凉爽啊!青山绿水映入我的眼中,景色怡人啊!

设计模式专题之组合模式讲解

相关文章:

你感兴趣的文章:

标签云: