GofPatterns Gofpatterns





Behavioral Patterns  «Prev  Next»

Strategy Pattern Code in Java

The following is an example of a file compression tool where a zip or rar file is created.
The Strategy interface is defined first:
package com.java.behavioral.strategy;
//Strategy Interface
public interface CompressionStrategy{
  public void compressFiles(ArrayList files);
}
Two implementations are provided,
  1. one for zip and
  2. one for rar
package com.java.behavioral.strategy;
public class ZipCompressionStrategy implements CompressionStrategy{  
  public void compressFiles(ArrayList<File> files){
    //using ZIP approach
  }
}
package com.java.behavioral.strategy;
public class RarCompressionStrategy implements CompressionStrategy{
   public void compressFiles(ArrayList<File > files){
     //using RAR approach
   }
}


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 strategy;   

   //this can be set at runtime by the application preferences
   public void setCompressionStrategy(CompressionStrategy strategy){
       this.strategy = strategy;  
   }

  //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);     
 }
}