I am going through the book Head First Design Pattern
, and the first design pattern that I encountered was Strategy Design Pattern. I found it fairly easy to understand and implement, but while implementing I am facing one problem that I don't know how can we call the constructor of the behavioral class.
A snapshot from the book :
Here I am talking about how to call the constructor of FlyWithWings, Quack etc
classes.
I will give an example of Strategy Design Pattern to understand it in a better way :
//Strategy Interface
public interface CompressionStrategy {
public void compressFiles(ArrayList<File> files);
}
public class ZipCompressionStrategy implements CompressionStrategy {
public void compressFiles(ArrayList<File> files) {
//using ZIP approach
}
}
public class RarCompressionStrategy implements CompressionStrategy {
public void compressFiles(ArrayList<File> files) {
//using RAR approach
}
}
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);
}
}
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);
}
}
So in the above example RarCompressionStrategy
and ZipCompressionStrategy
are the behavioral class. So can it be possible to trigger their parametrized constructor class of these behavioral classes from CompressionContext
class?
Aucun commentaire:
Enregistrer un commentaire