`
DavyJones2010
  • 浏览: 148284 次
  • 性别: Icon_minigender_1
  • 来自: 杭州
社区版块
存档分类
最新评论

DesignPattern: Composite Pattern

阅读更多

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

 

  • 大小: 22.9 KB
  • 大小: 28.7 KB
  • 大小: 16.3 KB
  • 大小: 30.6 KB
分享到:
评论

相关推荐

    36种最新设计模式整理

    Design Pattern: Composite 模式 40 Design Pattern: Decorator 模式 41 Design Pattern: Facade 模式 44 Design Pattern: Flyweight 模式 46 Design Pattern: Proxy 模式(一) 48 Design Pattern: Proxy 模式(二...

    java设计模式源码-DesignPattern:设计模式(Java实现源码)

    java ...组合模式(compositePattern) 装饰器模式(decoratorPattern) 外观模式(facadePattern) 享元模式(flyweightPattern) 代理模式(proxyPattern) 责任链模式(chainPattern) 命令模式(commandPatter

    C++设计模式(Design Pattern)范例源代码

    23种设计模式(Design Pattern)的C++实现范例,包括下面列出的各种模式,代码包含较详细注释。另外附上“设计模式迷你手册.chm”供参考。 注:项目在 VS2008 下使用。 创建型: 抽象工厂模式(Abstract Factory) 生成...

    单例模式源码java-DesignPattern:在个人自学阶段的23种设计模式代码的全部实现,全部使用Java编写,其中还包括各个设计模式在

    DesignPattern 在个人自学阶段的23种设计模式代码的全部实现,全部使用Java编写,其中还包括各个设计模式在源码中的使用,每种设计模式都举了一个简单的小例子来进行实现,并加以注释 包名解释 一、DesignPattern ...

    Homework 2.1-1.doc

    The following class diagram represents a design in factory method pattern to query the features of different types of auto insurances. See the source code for the implementation of the following class...

    《Java Design Patterns》高清完整英文PDF版

    Learn how to implement design patterns in Java: each pattern in Java Design Patterns is a complete implementation and the output is generated using Eclipse, making the code accessible to all....

    深入浅出设计模式中文

    Head First Design Pattern 中文版本 1 Welcome to Design Patterns: an introduction 1 2 Keeping your Objects in the know: the Observer Pattern 37 3 Decorating Objects: the Decorator Pattern 79 4 Baking ...

    Java.Design.Patterns.1537192353

    COMPOSITE PATTERN PROXY PATTERN FAÇADE PATTERN DECORATOR PATTERN FLYWEIGHT PATTERN TEMPLATE METHOD PATTERN MEDIATOR PATTERN CHAIN OF RESPONSIBILITY ... OBSERVER PATTERN STRATEGY PATTERN COMMAND ...

    uu-design-pattern:23种设计模式案例

    |- singleton 单例模式案例 |- structural(结构型模式) |- facade 外观模式案例 |- decorator 装饰器模式案例 |- adapter 适配器模式案例 |- flyweight 享元模式案例 |- composite 组合模式案例

    设计模式 design pattern

    4.8.2 Composite、Decorator与Proxy 145 第5章 行为模式 147 5.1 CHAIN OF RESPONSIBIL ITY(职责链) —对象行为型模式 147 5.2 COMMAND(命令)—对象行为型 模式 154 5.3 INTERPRETER(解释器)—类行为型 模式 ...

    design patterns elements of reusable object-oriented software

    ★第1章至第11章陆续介绍了设计模式:Strategy、Observer、Decorator、Abstract Factory、Factory Method、Singleton、Command、Adapter、Facade、TemplatMethod、Iterator、Composite、State、Proxy。 ★第12章介绍...

    Design.Patterns.Explained.Simply

    Composite Decorator Facade Flyweight Private Class Data Proxy Behavioral patterns Chain of Responsibility Command Interpreter Iterator Mediator Memento Null Object Observer State Strategy Template ...

    design-pattern-java.pdf

    桥接模式-Bridge Pattern 处理多维度变化——桥接模式(一) 处理多维度变化——桥接模式(二) 处理多维度变化——桥接模式(三) 处理多维度变化——桥接模式(四) 组合模式-Composite Pattern 树形结构的处理...

    Design Patterns Elements of Reusable Object-Oriented Software

    • What Is a Design Pattern? • Design Patterns in Smalltalk MVC • Describing Design Patterns • The Catalog of Design Patterns • Organizing the Catalog • How Design Patterns Solve Design ...

    C#3.0设计模式.pdf

    1. C# Meets Design Patterns . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1 About Patterns 2 About UML 3 About C# 3.0 5 About the Examples 6 2. Structural ...

    CoreJava-DesignPattern

    CoreJava-DesignPattern 创意设计模式 -- Abstract Factory - Done -- Builder - Done -- Factory Method -- Object Pool -- Prototype - Done -- Singleton - Done 结构设计模式 -- Adapter -- Bridge -- ...

    design-pattern-detection

    设计模式检测该项目是使用Static Analisys自动检测Java项目源代码中实现的软件... 要检测的其他模式:Composite 和 Mediatordesign 模式。 可以添加更多基于静态分析的模式检测方法。 它还包含可用于测试的示例源代码。

    DesignPatternUtil

    The Java Design Pattern Utilities contains: Command,Composite,Observer,ProtoType,Singleton,State,COR patterns. The tools helps you create Java application with GOF Patterns more easily.

    Apress.Pro.Design.Patterns.in.Swift

    The Composite Pattern Chapter 16. The Facade Pattern Chapter 17. The Flyweight Pattern Chapter 18. The Proxy Pattern Part 4 - The Behavioral Patterns Chapter 19. The Chain of Responsibility Pattern ...

Global site tag (gtag.js) - Google Analytics