Individual objects as well as the composite objects can be represented with the Composite Design Pattern. Composite pattern represents these objects with a tree structure. Suppose, Within a company, there is an employee hierarchy where a manager has its subordinates, Project Leader also have the subordinates, while the developer has no subordinates.
Benefits : It is more flexible as compared to the static inheritance. It simplifies coding by implementing each feature in a class. It enhances the capability of an object as the new classes are created to add new features and make some changes.
Usage: This design pattern is used when the responsibilities are needed to be added dynamically to the individual objects without affecting other objects. Where an object's responsibilities may vary from time to time.
Now, lets try to solve the above problem technically.
Develop a class "Employee" having the getters and setters for the attributes empname, empsal and emp subordinates.
For example, General Manager may have several employee and some of them are Managers, further these managers have several employees. To illustrate all these things, lets design a simple Manager class.
Here is the "Test" class that shows the information about the "Manager" class.
Here is the output of the program :
|C:\> java Test
Employee Zulfiqar Salary: $90.0
Employee Amit Salary: $90.0
Employee Aquil Salary: $80.0
Employee Ravi Salary: $70.0
Employee Vinod Salary: $50.0
The above example concludes that the composite pattern allows us to create a tree like structure for both simple and complex objects.
Rs. 20,000 US$ 300
Today: Rs. 10,000 US$150
Course Duration: 30 hrs
Posted on: December 13, 2008 If you enjoyed this post then why not add us on Google+? Add us to your Circles