- What problem does Composite pattern solve?
Suppose we have some classes, like:
- Manager
- SalesPerson
that have similar functionality of payExpenses()
How are we going to execute payExpenses() for all Managers and all SalesPersons?
Do we really need to call payExpenses() for each type of these 2 entities, like:
- manager.payExpenses()
- manager.payExpenses()
- salesPerson.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 and SalesPersons will implement the same Payee interface
For example, Manager:
For example, Manager:
public class Manager implements Payee {
public void payExpenses(int amount) {
// pay manager procedure...
}
}
3. Lets' replace manager and salesPerson references with the new Payee interface type
Before:
Before:
After:
Suppose jane is a Manager, bob and sue are SalesPerson-s
Δεν υπάρχουν σχόλια:
Δημοσίευση σχολίου
What may be missing, or could get better?