Composite Design Pattern
1) Motivation:
There are many times when a program need to manipulate a tree data structure and it is necessary to treat both Branches as well as Leaf Nodes uniformly.
Consider for example a program that manipulates a file system. A file system is a tree structure that contains Branches which are folders as well as Leaf Nodes which are files.
Note that a folder object ususally contains one or more files or folder objects and thus is a complex object where a file is a simple object.
Note also that since files and folders had many operations and attributes in common, such as moving or copying a file or a folder, listing file or folder attributes such as file name and size.
It would be easier and more convenient to treat both file and folder objects uniformly by defining a File System Resource Interface.
2) Intent:
The intent of this pattern is to compose objects into tree structures to represent part-whole hierarchies.
Composite lets client treat individual objects and compositions objects uniformly.
3) Implementation:
1> Component:
Component is the abstraction of leafs and composites. It defines the interface that must be implemented by the object in the composition.
For example, a file resource system defines move, copy, reName and getSize methods for files and folders.
2> Leaf:
Leafs are objects that have no children. They implement services described by the Component interface.
For example, a file object implements move, copy, reName as well as getSize methods which are related to the component interface.
3> Composite:
A composite stores child components in addition to implementing methods defined by the Component interface.
Composites implements methods defined in the Component interface by delegating to child components.
In addition, composites provide additional methods for adding, removing as well as getting components.
4> Client:
The Cilent manipulate objects in the hierarchy using the Component interface.
A Client has a reference to a tree data structure and needs to perform operations on all nodes independent of the fact that a node might be a brach or a leaf.
The Client simply obtains a reference to the required node using the Component interface, and deals with the node using the interface.
It doesn't matter if the node is a Leaf or a Composite.
4) Applicablity & Examples:
The composite pattern applies when there is a part-whole hierarchy of objects and a client needs to deal with object uniformly regardless of the fact that an object might be a leaf or a branch.
Example: Graphics Drawing Editor
In graphics editors a shape can be basic or complex.
An example of a simple shape is a Line, where a complex shape is a rectangle which is made of four Line objects.
Since shapes have many operations in common such as rendering the shape to screen,
and since shapes follow a part-whole hierarchy, composite pattern can be used to enable the program to deal with all shapes uniformly.
package edu.xmu.oop.composite; public interface Shape { public void render(); }
package edu.xmu.oop.composite; public class LineShape implements Shape { public void render() { System.out.println("Render [LineShape]"); } }
package edu.xmu.oop.composite; public class RectangleShape implements Shape { public void render() { System.out.println("Render [RectangleShape]"); } }
package edu.xmu.oop.composite; import java.util.ArrayList; import java.util.List; public class ComplexShape implements Shape { private List<Shape> components = new ArrayList<Shape>(); public void render() { System.out.println("Start render [ComplexShape]"); for (Shape shape : components) { shape.render(); } System.out.println("Finished render [ComplexShape]"); } public void addComponent(Shape shape) { components.add(shape); } public void removeComponent(Shape shape) { components.remove(shape); } }
package edu.xmu.oop.composite; public class GraphicsEditor { public void display(Shape shape) { shape.render(); } }
package edu.xmu.oop.composite; import org.junit.Before; import org.junit.Test; public class GraphicsEditorTest { private GraphicsEditor graphicsEditor; private Shape complexShape1; @Before public void setUp() { graphicsEditor = new GraphicsEditor(); complexShape1 = new ComplexShape(); ((ComplexShape) complexShape1).addComponent(new LineShape()); // We have to cast complexShape1 to ComplexShape ((ComplexShape) complexShape1).addComponent(new RectangleShape());// We have to cast complexShape1 to ComplexShape Shape complexShape2 = new ComplexShape(); ((ComplexShape) complexShape2).addComponent(new LineShape());// We have to cast complexShape2 to ComplexShape ((ComplexShape) complexShape2).addComponent(new LineShape());// We have to cast complexShape2 to ComplexShape ((ComplexShape) complexShape2).addComponent(new RectangleShape());// We have to cast complexShape2 to ComplexShape ((ComplexShape) complexShape1).addComponent(complexShape2);// We have to cast complexShape1 to ComplexShape } @Test public void displayTest() { graphicsEditor.display(complexShape1); } }
And we can see in the diagram below that the objects are organized as a tree.
5) Alternative Implementations:
Note that in previous example, there were times when we have to avoid dealing with composite objects through the Shape interface,
And we have specifically dealt with them as composites(when using the method addComponent()).
To avoid such situations and to further increase uniformity, one can add method to add, remove and get child components to the Shape interface.
6) Related Patterns:
1> Decorator Pattern:
Decorator is often used with Composite.
When Decorator and Composite are used together, they will usually have a common parent class,
So Decorator will have to support the Component interface with operations like Add, Remove and GetChild.
Reference Links:
1) http://www.oodesign.com/composite-pattern.html
2) http://en.wikipedia.org/wiki/Composite_pattern
相关推荐
本资源“DesignPattern::pencil:设计模式_java实现以及详解”提供了一套详细的学习材料,帮助开发者理解和应用设计模式。 该资源的作者是“养码青年-Style”,他通过这个项目记录了自己的设计模式学习过程。鼓励...
9. 组合模式(Composite Pattern): 组合模式将对象组合成树形结构以表示“部分-整体”的层次结构。在C#中,组合模式通常用于处理具有树状结构的数据,如文件系统、UI组件树等,提供一致的接口来操作单个对象和对象...
"DesignPattern:C#设计模式示例"这个资源很可能是包含多个C#实现的设计模式示例代码库。 设计模式通常分为三类:创建型、结构型和行为型。每种模式都解决了特定场景下的问题,并提供了良好的代码组织和扩展性。 ...
java ...组合模式(compositePattern) 装饰器模式(decoratorPattern) 外观模式(facadePattern) 享元模式(flyweightPattern) 代理模式(proxyPattern) 责任链模式(chainPattern) 命令模式(commandPatter
设计模式是软件工程中的一种最佳实践,用于解决在软件设计中常见的...以上就是这个DesignPattern小Demo中可能会涵盖的设计模式,通过这些模式的实例,你可以更好地理解和应用它们到实际项目中,提升你的Java编程能力。
DesignPattern-master这个压缩包可能包含了一个关于设计模式的项目或者教程资源。 设计模式分为三类:创建型模式(Creational Patterns)、结构型模式(Structural Patterns)和行为型模式(Behavioral Patterns)...
在"DesignPattern-master"这个压缩包中,你可能找到的文件结构和内容包括: 1. **单例模式(Singleton)**:确保一个类只有一个实例,并提供一个全局访问点。在.NET中,通常使用静态属性或双重检查锁定来实现。 2....
在"designPattern-master"这个项目中,你可以期待找到以上所有或部分设计模式的Java代码实现,这将是一个宝贵的资源,可以帮助你深入理解和掌握这些模式的实际运用,提升你的编程技能。通过阅读和实践这些代码,你...
设计模式(Design Pattern)是软件工程中的一种经验总结,它是在特定上下文中为解决常见问题而提出的一套可复用的解决方案。设计模式并不直接实现为代码,而是提供了一种在面向对象设计中如何处理常见问题的指南。...
9. 组合模式(Composite Pattern):将对象组合成树形结构以表示“部分-整体”的层次结构。组合模式使得用户对单个对象和组合对象的使用具有一致性。 10. 装饰器模式(Decorator Pattern):动态地给一个对象添加...
这个名为"DesignPattern"的压缩包文件很可能包含了一个Java实现的各种设计模式的示例程序。 在这个"DesignPattern-master"目录中,我们可以期待找到一系列与设计模式相关的Java源代码文件(.java),每个文件或...
### Design Pattern 简明手册知识点详述 #### 一、接口型(interface)模式 **1. Adapter(适配器模式)** - **定义**:允许一个类接口与另一个不兼容的类接口协同工作。 - **分类**: - **继承型Adapter**:通过...
在“阅读java源码-JavaDesignPattern:23种设计模式Java实现”中,我们将深入探讨这23种设计模式的Java实现。 1. **创建型模式**(Creational Patterns): - **单例模式(Singleton)**:确保一个类只有一个实例,...
在软件开发领域,设计模式是经过时间和实践验证的解决方案,用于解决常见的编程问题。...在“Java-DesignPattern-master”压缩包中,你可能会找到关于这些模式的实例和代码演示,通过实际操作来深入理解和掌握它们。
23种设计模式(Design Pattern)的C++实现范例,包括下面列出的各种模式,代码包含较详细注释。另外附上“设计模式迷你手册.chm”供参考。 注:项目在 VS2008 下使用。 创建型: 抽象工厂模式(Abstract Factory) 生成...
在本文中,我们将深入探讨设计模式的核心概念,并结合"Head First DesignPattern_src"中的源码,详细解析一些关键的设计模式。 1. 单例模式(Singleton): 单例模式确保一个类只有一个实例,并提供全局访问点。在...
在`DesignPattern-master`这个压缩包中,你可能会看到以上提到的各种设计模式的Swift实现。通过阅读和分析这些源码,你可以更深入地了解如何在实际项目中应用这些模式,以及它们在Swift语法和特性下的具体表现。同时...
10. **组合模式(Composite)**:将对象组织成树形结构,可以以统一的方式处理单个对象和对象集合。 11. **享元模式(Flyweight)**:通过共享技术,有效地支持大量细粒度的对象,减少内存占用。 12. **命令模式...
设计模式是软件工程中的一种最佳实践,它是在特定情境下解决常见问题的经验总结。...在DesignPattern-master这个压缩包中,你可以找到关于这些模式的详细讲解和实例代码,为你的Java开发之旅提供宝贵的参考资料。