Strategy Pattern V/S Decorator Pattern
Solution 1:
The strategy pattern allows you to change the implementation of something used at runtime.
The decorator pattern allows you augment (or add to) existing functionality with additional functionality at run time.
The key difference is in the change vs augment
In one of the questions you linked to it also points out that with the strategy pattern the consumer is aware that the different options exist, whereas with the decorator pattern the consumer would not be aware of the additional functionality.
As an example, imagine you are writing something to sort a collection of elements. So you write an interface ISortingStrategy
you can then implement several different sorting strategies BubbleSortStrategy
, QuickSortStrategy
, RadixSortStrategy
, then your application, based on some criteria of the existing list chooses the most appropriate strategy to use to sort the list. So for example if the list has fewer than 10 items we will use RadixSortStrategy
, if fewer than 10 items have been added to the list since the last sort we will use BubbleSortStrategy
otherwise we will use QuickSortStrategy
.
We are changing the type of sort at runtime (to be more efficient based on some extra information.) this is the strategy pattern.
Now imagine someone asks us to provide a log of how often each sorting algorithm is used to do an actual sort and to restrict sorting to admin users. We can add both of these pieces of functionality by creating a decorator which enhances any ISortingStrategy
. We could create a decorator which logs that it was used to sort something and the type of the decorated sorting strategy. And we could add another decorator that checks if the current user is an administrator before calling the decorated sorting strategy.
Here we are adding new functionality to any sorting strategy using the decorator, but are not swapping out the core sorting functionality (we used the different strategies to change that)
Here is an example of how the decorators might look:
public interface ISortingStrategy
{
void Sort(IList<int> listToSort);
}
public class LoggingDecorator : ISortingStrategy
{
private ISortingStrategy decorated;
public LoggingDecorator(ISortingStrategy decorated)
{
this.decorated=decorated;
}
void Sort(IList<int> listToSort)
{
Log("sorting using the strategy: " + decorated.ToString();
decorated.Sort(listToSort);
}
}
public class AuthorisingDecorator : ISortingStrategy
{
private ISortingStrategy decorated;
public AuthorisingDecorator(ISortingStrategy decorated)
{
this.decorated=decorated;
}
void Sort(IList<int> listToSort)
{
if (CurrentUserIsAdministrator())
{
decorated.Sort(listToSort);
}
else
{
throw new UserNotAuthorizedException("Only administrators are allowed to sort");
}
}
}
Solution 2:
Strategy_pattern
- Defines a family of algorithms,
- Encapsulates each algorithm, and
- Makes the algorithms interchangeable within that family.
Use Strategy pattern when you have to change algorithm dynamically at run time.
Decorator
Decorator pattern dynamically changes the functionality of an object at runtime without impacting the existing functionality of the objects.
When to use:
- Add additional functionalities/responsibilities dynamically
- Remove functionalities/responsibilities dynamically
- Avoid too much of sub-classing to add additional responsibilities.
Drawbacks:
- Overuse of Open Closed principle ( Open for extension and Closed for modification). Use this feature sparingly where the code is least likely changed.
- Too many small classes and will add maintenance overhead.
Key difference:
Strategy lets you change the guts of an object. Decorator lets you change the skin.
Few more useful posts:
When to Use the Decorator Pattern?
Real World Example of the Strategy Pattern
strategy by sourcemaking
Solution 3:
The strategy is pattern is used to "encapsulate what changes". It allows you to define algorithms that can be interchanged at runtime. For example (example taken from Head First Design Patterns):
Say you have a a duck simulator. You want to make your duck objects fly. You could use inheritance for this but it gets messy quickly. Some ducks can't fly (e.g. rubber ducks). The way to do this is to encapsulate what changes i.e. the fly behaviour into its own class that implement IFlybehaviour for example. You can then use composition instead of inheritance and inject the IFlybehaviour into your duck objects. You could also then have a method that sets this fly behaviour so the fly behaviour can be changed at runtime. This is essentially the strategy pattern.
The decorator pattern is used to add functionality to an object at runtime. It allows you to wrap objects within objects. Decorators must have the same supertype as the objects they decorate. This allows you to call a method on the "outmost wrapper" and you can then chain call this same method down through the layers of decorators. It is basically a more flexible approach than subclassing.
As to which ones you choose depends on the problem you want to solve. Do you want to have a family of algorthims that are interchangeable at runtime or do you want to dynamically add more functionality to an object at run time?
The book "Head first design patterns" explains this quite well (probably much better than me) IMO so it is worth a read if you get chance.
Good luck.
Solution 4:
It boils down to this: Use Strategy to choose one piece of core functionality. Use Decorator to add extra functionality. Strategy is the cake we're making and Decorator is all the pretty decorations we're adding to it.