设计模式8 - 组合模式Composite

组合模式用于在需要表示部分-整体层次结构时,使用树形结构组合对象。该模式让我们可以统一处理单个对象和对象组合。本文以乐高积木为例,通过Java实现这一设计模式,展示如何构建一个由基本积木块(叶节点)组成的各种结构,再将这些结构组合成房屋(组合节点)。


Composite Design Pattern

When we want to represent part-whole hierarchy, use tree structure and compose objects. We know tree structure what a tree structure is and some of us don’t know what a part-whole hierarchy is. A system consists of subsystems or components. Components can further be divided into smaller components. Further smaller components can be divided into smaller elements. This is a part-whole hierarchy.

Everything around us can be a candidate for part-whole hierarchy. Human body, a car, a computer, lego structure, etc. A car is made up of engine, tyre, … Engine is made up of electrical components, valves, … Electrical components is made up of chips, transistor, … Like this a component is part of a whole system. This hierarchy can be represented as a tree structure using composite design pattern.



“Compose objects into tree structures to represent part-whole hierarchies. Composite lets clients treat individual objects and compositions of objects uniformly.” is the intent by GoF.

Real World Example

In this article, let us take a real world example of part-whole hierarchy and use composite design pattern using java. As a kid, I have spent huge amount of time with lego building blocks. Last week I bought my son an assorted kit lego and we spent the whole weekend together building structures.

Let us consider the game of building blocks to practice composite pattern. Assume that our kit has only three unique pieces ( 1, 2 and 4 blocks) and let us call these as primitive blocks as they will be the end nodes in the tree structure. Objective is to build a house and it will be a step by step process. First using primitive blocks, we should construct multiple windows, doors, walls, floor and let us call these structures. Then use all these structure to create a house.


Primitive blocks combined together gives a structure. Multiple structures assembled together gives a house.

Important Points

  • Importance of composite pattern is, the group of objects should be treated similarly as a single object.
  • Manipulating a single object should be as similar to manipulating a group of objects. In sync with our example, we join primitive blocks to create structures and similarly join structures to create house.
  • Recursive formation and tree structure for composite should be noted.
  • Clients access the whole hierarchy through the components and they are not aware about if they are dealing with leaf or composites.

Tree for Composite

When we get a recursive structure the obvious choice for implementation is a tree. In composite design pattern, the part-whole hierarchy can be represented as a tree. Leaves (end nodes) of a tree being the primitive elements and the tree being the composite structure.



Uml Design for Composite Pattern

Component: (structure)

  1. Component is at the top of hierarchy. It is an abstraction for the composite.
  2. It declares the interface for objects in composition.
  3. (optional) defines an interface for accessing a component’s parent in the recursive structure, and implements it if that’s appropriate.

Leaf: (primitive blocks)

  1. The end nodes of the tree and will not have any child.
  2. Defines the behaviour for single objects in the composition

Composite: (group)

  1. Consists of child components and defines behaviour for them
  2. Implements the child related operations.

Composite Pattern Implementation

public class Block implements Group {
    public void assemble() {
        System.out.println("Block");
    }
}

public interface Group {
    public void assemble();
}

import java.util.ArrayList;
import java.util.List;
 
public class Structure implements Group {
  // Collection of child groups.
  private List<Group> groups = new ArrayList<Group>();
 
  public void assemble() {
    for (Group group : groups) {
      group.assemble();
    }
  }
 
  // Adds the group to the structure.
  public void add(Group group) {
    groups.add(group);
  }
 
  // Removes the group from the structure.
  public void remove(Group group) {
    groups.remove(group);
  }
}

public class ImplementComposite {
   public static void main(String[] args) {
          //Initialize three blocks
          Block block1 = new Block();
          Block block2 = new Block();
          Block block3 = new Block();
 
          //Initialize three structure
          Structure structure = new Structure();
          Structure structure1 = new Structure();
          Structure structure2 = new Structure();
 
          //Composes the groups
          structure1.add(block1);
          structure1.add(block2);
 
          structure2.add(block3);
 
          structure.add(structure1);
          structure.add(structure2);
 
          structure.assemble();
      }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值