Composite PatternA Composite Pattern says that just "allow clients to operate in generic manner on objects that may or may not represent a hierarchy of objects". Advantage of Composite Design Pattern
Usage of Composite PatternIt is used:
UML for Composite PatternElements used in Composite Pattern:Let's see the 4 elements of composte pattern. 1) Component
2) Leaf
3) Composite
4) Client
Note:The work flow of above general UML is as follows. Client uses the component class interface to interact with objects in the composition structure. If recipient is the leaf then request will be handled directly. If recipient is a composite, then it usually forwards the request to its child for performing the additional operations. Example of Composite PatternWe can easily understand the example of composite design pattern by the UML diagram given below: Implementation of above UML:Step 1Create an Employee interface that will be treated as a component. Step 2Create a BankManager class that will be treated as a Composite and implements Employee interface. File: BankManager.java Step 3Create a Cashier class that will be treated as a leaf and it will implement to the Employee interface. File: Cashier.java Step 4Create a Accountant class that will also be treated as a leaf and it will implement to the Employee interface. File: Accountant.java Step 5Create a CompositePatternDemo class that will also be treated as a Client and ii will use the Employee interface. File: CompositePatternDemo.java OutputNext TopicDecorator Pattern |