本文主要是介绍设计模式学习笔记八——Composite模式,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
动机:客户代码过多地依赖于对象容器复杂的内部实现结构,对象容器内部实现结构(而非抽象接口)的变化将引起客户代码的频繁变化,带来了代码维护性、扩展性等弊端。本模式通过将对象组合成树形结构以表示“部分-整体”的层次结构,让组合对象实现自身的复杂结构,使得用户对单个对象和组合对象的使用具有一致性。应用:ASP.NET子父控件关系。
场景:以树为例,叶子为最低级原子节点,树为容器,可以包括子树和叶子。需要使客户程序对树和叶子的处理一致,保持透明性,而不需要关心处理的是树还是叶子。
结构:

代码实现
























































































































要点:
1、本模式采用树形结构来实现普遍存在的对象容器,从而将“一对多” 的关系转化为“一对一”的关系,使得客户代码可以一致地处理单个对象和对象容器,而无需关心处理的是单个对象还是组合的对象容器。
2、将“客户代码与复杂的对象容器结构”解耦是本模式的核心思想,解耦之后,客户代码将与纯粹的抽象接口——而非对象容器的复杂内部实现结构——发生依赖关系,从而能够应对变化。
3、本模式中,将单个对象不具有的操作的(如Add和Remove)定义于接口或抽象类中,还是组合对象中,需要从透明性和安全性两方面平衡考虑。应用此模式,更强调透明性,所以有可能违背面向对象的“单一职责”原则。
4、本模式在具体实现中,可以让父对象中的子对象反向追溯;如果父对象有频繁的遍历需求,可使用缓存来改善性能。
这篇关于设计模式学习笔记八——Composite模式的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!