Τρίτη 25 Ιανουαρίου 2022

Composite pattern

  • What problem does Composite pattern solve?



Suppose we have some classes, like:
- Manager
- SalesPerson
- SalesTeam

that have similar functionality of payExpenses()

How are we going to execute payExpenses() for all Managers, all SalesPersons and all SalesTeams?

Do we really need to call payExpenses() for each type of these 3 entities, like:
- manager.payExpenses()
- salesPerson.payExpenses()
- salesTeam.payExpenses()
?

No.
We could have only one payExpenses() to handle all these cases,
in order to
-  reduce code duplication 
-  improve code readability 
-  improve code extendability


  • How does Composite pattern solve this?


- We will just have one Payee interface's payExpenses() method to handle all cases
- All related entities will implement the same Payee interface


1. Create a Payee interface with one payExpenses() method




2. Manager, SalesPerson and SalesTeams will implement the same Payee interface

    public class Manager implements Payee {

      public void payExpenses(int amount) {
        // pay manager procedure...
      }

   }


3. In addition, SalesTeam will replace manager and salesPerson references with the new Payee interface type

Old SalesTeam:

New SalesTeam:

4. Finally, in our Main method we use the new structure, like:







Δεν υπάρχουν σχόλια:

Δημοσίευση σχολίου

What may be missing, or could get better?