A class needs to manage collections of different types of objects. For example, a library contains books, magazines, and recordings. We could provide the Library class with a separate collection for each item:
Here's the start of the implementation:
class Library {
Set<Book> books;
Set<Magazine> magazines;
Set<Recording> recordings;
// etc.
}
Unfortunately, this means three sets of add, remove, iterate, and element methods.
This gets especially cumbersome when the library decides to collect prints:
Create an interface and require all managed elements to implement it. The manager should only refer to the interface:
We can also require implementing classes to implement methods specified in the interface:
Note: If the method of calculating value is the same for all items, then it would be better to change Item to a class and implement the getValue method there.