Composite design pattern in java

CodeProjectComposite design patten allows you to have a tree structure and ask each node in the tree structure to perform a task.You can take real life example of a organization.It have general managers and under general managers, there can be managers and  under managers there can be developers.Now you can set a tree structure and ask each node to perform common operation like getSalary().

As described by Gof:
“Compose objects into tree structure to represent part-whole hierarchies.Composite lets client treat individual objects and compositions of objects uniformly”.

Composite design pattern treats each node in two ways-Composite or leaf.Composite means it can have other objects below it.leaf means it has no objects below it.

Tree structure:

When to use it:

  • you want to represent part-whole hierachies of objects.
  • you want client to be able to ignore difference between compositions of objects and individual objects.Clients will treat all objects in the composite structure uniformly.

UML Diagram for Composite design pattern:

Elements:

  • Component
    • declares interface for objects in composition.
    • implements deafault behaviour for the interface common to all classes as appropriate.
    • declares an interface for accessing and managing its child components.
  • Leaf
    • represents leaf objects in the composition.A leaf has no children.
    • defines behaviour for primitive objects in the composition.
  • Composite
    • defines behaviour for components having children.
    • stores child components.
    • implements child related operations in the component interface.
  • Client
    • manipulates objects in the composition through the component interface.

WorkFlow:

Client use the component class interface to interact with objects in the composition structure.if recipient is a leaf then request is handled directly.If recipient is a composite,then it usually forwards request to its child components,possibly performing additional operations before and after forwarding.

Recursion:

What makes the Composite pattern one of the most beautiful is the power of recursion. I can explain this with the same organization example. You want to find the total salary paid to all employees of the organization. It is nothing but the salary of CEO + the salary paid to all the departments. What is the salary of a department? It is the salary of the department head + the salary of all projects. What is the total salary of a project? It is the salary of the project manager + the salary of all the project members. In short, the salary of anything is the salary of self + the salary of all its sub groups.

Example:

In a small organization,there are 5 employees.At top position,there is 1 general manager.Under general manager,there are two employees,one is manager and other is developer and further manager has two developers working under him.We want to print name and salary of all employees from top to bottom.

Tree structure for example:

UML diagram for above example:

Comparing from above generic elements.Our example consist of following elements.

  • Manager(Composite)
  • Developer(Leaf)
  • Employee(Component)

Java code for all above classes:

First we will create component inrteface.It represents object in composition .It has all common operation that will be applicable to both manager and developer.
Employee.java(Component) :
Now we will create manager(composite class).Key point here is that all common method delegates its operations to child objects.It has method to access and modify its children.

Manager.java(Composite):
We will create developer class.This class is leaf node so all operations related to accessing children will be empty as it has no children.
Developer.java(Leaf):

CompositeDesignPatternMain.java:
Output:

Disadvantages:

  • Once tree structure is defined,comosite design makes tree overly general.
  • Leaf class have to create some methods which has to empty.

Usage in JDK:

  • java.util.Map#putAll(Map)
  • java.util.List#addAll(Collection)
  • java.util.Set#addAll(Collection)
  • java.nio.ByteBuffer#put(ByteBuffer) (also on CharBuffer, ShortBuffer, IntBuffer, LongBuffer, FloatBuffer and DoubleBuffer)
  • java.awt.Container#add(Component)

Related Posts

  • Detect keypress in Python
    12 June

    Detect keypress in Python

    Table of ContentsUsing the keyboard module to detect keypress in PythonUsing the pynput module to detect keypress in PythonUsing the msvcrt module to detect keypress in Python Python allows us to work with user input in its programs. We can also work with hardware devices in Python. In this article, we will discuss how to […]

  • Write a list to a file in Python
    12 June

    Write a list to a file in python

    Table of ContentsUsing the write() function to write a list to a file in PythonUsing the writelines() function to write a list to a file in PythonUsing the pickle.dump() function to write a list to a file in PythonUsing the json.dump() function to write a list to a file in PythonUsing the unpack operator * […]

  • Copy a dictionary in Python
    12 June

    7 ways to copy a dictionary in python

    Table of ContentsUsing the copy() function to copy a dictionary in PythonUsing the deepcopy() function to copy a dictionary in PythonUsing the dict() function to copy a dictionary in PythonUsing the unpack operator ** to copy a dictionary in PythonUsing the update() function to copy a dictionary in PythonUsing the dictionary comprehension method to copy […]

  • Escape quotes in Python
    11 June

    Escape quotes in Python

    Table of ContentsUsing \ to escape quotes in PythonUsing \ with replace() to escape quotes in PythonUsing json.dumps to escape quotes in PythonUsing triple single or double quotes to escape quotes in pythonUse r to include \ and quotes in String 💡 Outline You can use \ to escape quotes in Python. If you want […]

  • Merge two vectors in C++
    11 June

    Merge two Vectors in C++

    Table of ContentsUsing merge() to merge two vectors in C++Using set_union() to merge two vectors in C++Using insert() to combine two vectors in C++Using move() & back_inserter to merge two vectors in C++Using copy() and back_inserter to concatenate two vectors in C++Using make_move_iterator() and insert() to merge two vectors in C++Conclusion vectors are like dynamic […]

  • C++ random number between 0 and 1
    11 June

    C++ random number between 0 and 1

    Table of ContentsUsing the rand() function to generate random number between 0 and 1 in C++Using the std::uniform_real_distribution() function to generate random number between 0 and 1 in C++ Random numbers are frequently used in programming for test case generation, cryptography, and other related purposes. In this tutorial, we will generate random number between 0 […]

Leave a Reply

Your email address will not be published. Required fields are marked *

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.