The
context will provide a way for the client to compress the files.
Assume there is a preferences setting in our application that sets which compression algorithm to use.
We can change our strategy using the setCompressionStrategy method in the Context.
package com.java.behavioral.strategy;
public class CompressionContext{
private CompressionStrategy str;
//this can be set at runtime by the application preferences
public void setCompressionStrategy(CompressionStrategy strat){
this.str = strat;
}
//use the strategy
public void createArchive(ArrayList<File> files){
strategy.compressFiles(files);
}
}
All the client has to do now is pass through the files to the CompressionContext
package com.java.behavioral.strategy;
public class Client{
public static void main(String[] args){
CompressionContext ctx = new CompressionContext();
//we could assume context is already set by preferences
ctx.setCompressionStrategy(new ZipCompressionStrategy());
//get a list of files
...
ctx.createArchive(fileList);
}
}