Composite Design Pattern

overview: Composite Design Pattern is a structural design pattern that lets you compose objects into tree structures and then work with these structure as if they were individual objects.

Structural design pattern are design patterns that ease the design by identifying a simple way to realize relationships between entities.

When to use Composite Design Pattern

  • When application has hierarchical structure and needs generic functionality across the structure
  • When application needs to aggregate data across a hierarchy

reference: https://howtodoinjava.com/design-patterns/structural/composite-design-pattern/

How to implement

  1. Make sure that the core model of your app can be represented as a tree structure. Try to break it down into simple elements and containers. Remember that containers must be able to contain both simple elements and other containers.
  2. Declare the component interface with a list of methods that make sense for both simple and complex components.
  3. Create a leaf class to represent simple elements. A program may have multiple different leaf classes.
  4. Create a container class to represent complex elements. In this class, provide an array field for storing references to sub-elements. The array must be able to store both leaves and containers, so make sure it’s declared with the component interface type.While implementing the methods of the component interface, remember that a container is supposed to be delegating most of the work to sub-elements.
  5. Finally, define the methods for adding and removal of child elements in the container.

reference: https://refactoring.guru/design-patterns/composite

Leave a comment

Design a site like this with WordPress.com
Get started