What is the difference between Strategy pattern and Delegation pattern (not delegates)?
In the Strategy pattern, the Context behavior changes once by injecting a specific strategy and remains unchanged for the rest of its lifespan. Conversely, in the State pattern, the Context behavior can be changed dynamically during the rest of its lifespan by switching between its States.
The strategy design pattern in Java is used to encapsulate a related set of algorithms to provide runtime flexibility to the client. The client can choose any algorithm at runtime, without changing the Context class, which uses a Strategy object.
The Strategy pattern is used in situations where you know that you want to swap out implementations. As an example, you might want to format data in different ways - you could use the strategy pattern to swap out an XML formatter or CSV formatter, etc.
The State pattern is a specialization of the Strategy pattern and is so close to it. As you can see, the State pattern almost looks like the Strategy pattern. And as Strategy, if we want to add a new payment gateway, all we have to do is adding a new State which also respects the OCP.
the strategy pattern is a very specific design solution to a common software problem. the strategy pattern implies that there will be
delegation is more a principal than a pattern. delegation implies that instead of having a single object be in charge of everything, it delegates responsibilities to other objects. the reason this is a common technique is that it enforces two even more fundamental principals of software development by lessening coupling and increasing cohesiveness.
Having said all that, don't worry about patterns. Focus on the principals and if you feel your solution could be improved upon - look to the patterns to see if there is a better mousetrap. If you focus on patterns instead of principals, you will find yourself getting lost in all the patterns and implementing patterns for the sake of implementing patterns...
"Delegation" isn't really a design-pattern, it's more of a general programming technique, where component A delegates the task (whatever kind of task that may be) to component B. Delegation can be used in many contexts.
The Strategy pattern,on the other hand, is a specific pattern which typically makes heavy use of delegation as an implementation detail.
For example, you might implement the strategy pattern and invoke it using
strategy.execute(x)
The strategy pattern involves having various implementations of your Strategy interface, and selecting the appropriate implementation at runtime. The act of invoking that implementation is delegation.
So it's not either/or, the concepts are complimentary.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With