I'm learning about the Strategy Pattern and it seems like an amazing alternative to inheritance. I keep thinking about use-cases for it but there's this thing I keep struggling with when I try to connect the dots:
How does this work when my objects are heterogeneous.
So, what do I mean by that? The easiest way to explain is with an example I heard. Someone tried to explain this pattern by telling me "Imagine you have a List and the list should be Sortable. You could implement the interface Sortable and add the logic there, but a better alternative is to use composition over inheritance and pass the Sortable behavior to the list when it is constructed, that way you can reuse the sort logic between different types of lists AND you can switch the sorting strategy on the list at runtime"
Cool, so that explanation has the 3 main points I see in the strategy pattern:
- It favors composition over inheritance, making the code more flexible and maintainable.
- Because we're not implementing an interface, we are following DRY. If two different lists need the same sorting logic, they won't have to repeat the code in their @Override method. We can reuse because of composition.
- We could swap the behavior at runtime, which follows the Open/Close principle.
What keeps bugging me is that in order to sort a list we need a lot of information about the list. There are many many types of lists and they all have different internal structures. If the objects are heterogeneus, it would be pretty hard to have a sorting strategy that can be applied to two different types of Lists.
Imagine I have a LinkedList, an ArrayList and a DoublyLinkedList. In order to sort each one of these, I need to dig into the actual state, structures or internals (whatever you want to call them) of each implementation. So, it would be pretty hard to create a strategy that can operate on all of these lists.
- How does the Strategy pattern actually work in these cases?
- Or it isn't meant to be used with heterogeneous objects at all?
- Should strategy be used only if the strategy doesn't need to know any internals of the objects?
- Should it be used only if all the objects can provide the same information to the strategy in order to work?
If the strategy depends on the internals of the objects, it wouldn't be reusable... So, is there any real-life example that can shed light on the actual value of this pattern?
I don't have a final question per se (I asked many questions), but I think my point and concern is clear.
Aucun commentaire:
Enregistrer un commentaire