Search code examples
javadesign-patternsstrategy-pattern

Why we need Context class in strategy design pattern?


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


Solution

  • 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.