Reputation: 2281
Why need Context class in strategy pattern?
for example, i want to compress files using either zip or rar compression. we can solve this using strategy pattern with following files.
1.ICompressionStrategy...Its interface
2.ZipCompressionStrategy ..implements IcompressionStrategy
3.RarCompressionStrategy ..implements IcompressionStrategy
4.CompressionContext..Inject IcompressionStrategy
5.Client..Inject CompressionContext
In above scenario why we need CompressionContext class? why can't i inject IcompressionStrategy into Client class?
What is the advantage of using CompressionContext class in above scenario? can i avoid that?
Here is the example I am talking about
http://java.dzone.com/articles/design-patterns-strategy
Upvotes: 3
Views: 2908
Reputation: 437
Context
could decouple the client
and strategy
.
If there is no context
, when you want to change the strategy
's interface, you must change the interface in the client
too.
However, you may have no permission to change the client
or it may cause merge conflict.
But if there is a context
, you just need to change the achievement of context
and don't need to change the client
.
Upvotes: 3
Reputation: 691655
The idea of the strategy pattern is to customize some part of a task using a variable strategy.
The context, in the above example, does more than simply compressing a list of files. It could be, for example, a class that iterates through a folder hierarchy, selects files to compress, puts them in a list, uses the compression strategy, and writes the result of the compression to another location. This algorithm can be customized by providing a compression strategy, that is only used for the compression step of the whole algorithm.
Upvotes: 7