Structural Design Pattern. Composite Pattern.
Servus, my dear loyal fans, and today we are going to discuss the Composite Design Pattern and its implementation in Java. Lets us first define what exactly a Composite Pattern is.
A composite pattern is used where we need to treat a group of objects in a similar way as a single object. It composes objects in a way similar to a tree structure to represent part as well as a whole hierarchy. This type of design pattern comes under structural pattern as this pattern creates a tree structure of a group of objects.
The main objectives of this pattern are to create a class that contains a group of its own objects and to enable the group modification of the same objects.
We are going to demonstrate the use of this pattern in Java while creating a simple banking application. First of all, let us have a look at the UML diagram.
Imagine that we are helping to design a banking application. Customers in our banking application might have different accounts, such as Deposit and Savings. We are asked to prepare a design that can be useful to show the customer’s total account balance after merging all the account statements.
Here our Component class which was created as an abstract class and the corresponding methods will be overridden by the child classes.
The Savings class which is one of the Component’s child classes it has a name and balance as a parameter passes to a constructor which in turn helps to define the Savings class while instantiating it.
Here is another child class a Deposit class which is primarily the same as a Savings class.
Here is an Account class that combines the information from both Savings and Deposit Accounts. Therefore, from the code snippet provided above, we coordinate and retrieve data from Savings and Deposite classes through Component class which combines them all.
And a Client class is created by assigning the accounts to it. We can see it from the constructor in the code snippet provided.
Finally, a Composite is a pattern that is useful anytime you may need to selectively treat a group of objects that are part of a hierarchy as “the same” when they are in fact different.
Book- Eric Freeman, Elisabeth Freeman, Kathy Sierra, Bert Bates-Head First Design Patterns -OReilly (2008)
Feel free to check my github repository where I posted several design patterns implemented in Java — https://github.com/Farida004/Software-Design-and-Patterns
Thank you for your precious time ;) Good luck!