Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 453
Java P Avatar asked Oct 28 '25 05:10

Java P


2 Answers

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.

like image 164
JB Nizet Avatar answered Oct 30 '25 22:10

JB Nizet


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.

like image 37
hao li Avatar answered Oct 30 '25 21:10

hao li



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!