Click here to watch in Youtube : https://www.youtube.com/watch?v=CbBQQ06OcOo
Click the below Image to Enlarge
Strategy Design pattern - Implementation [Compress files] |
Strategy Design pattern - Implementation [Compress files] - Class Diagram |
CompressionStrategy.java
import java.io.File;
import java.util.ArrayList;
public interface CompressionStrategy
{
public void compressFiles( ArrayList<File> files,String compressedArchiveFileName );
}
ZipCompressionStrategy.java
import java.io.File;
import java.util.ArrayList;
public class ZipCompressionStrategy implements CompressionStrategy
{
public void compressFiles( ArrayList<File> files, String compressedArchiveFileName )
{
System.out.println("Files are compressed using zip approach: '" + compressedArchiveFileName
+ ".zip' file is created");
}
}
RarCompressionStrategy.java
import java.io.File;
import java.util.ArrayList;
public class RarCompressionStrategy implements CompressionStrategy
{
public void compressFiles( ArrayList<File> files, String compressedArchiveFileName )
{
System.out.println("Files are compressed using Rar approach: '" + compressedArchiveFileName
+ ".rar' file is created");
}
}
CompressionContext.java
import java.io.File;
import java.util.ArrayList;
public class CompressionContext
{
private CompressionStrategy strategy;
//Client will set what CompressionStrategy to use by calling this method
public void setCompressionStrategy( CompressionStrategy strategy )
{
this.strategy = strategy;
}
public void createArchive( ArrayList<File> files,String compressedArchiveFileName )
{
strategy.compressFiles(files,compressedArchiveFileName);
}
}
Client.java
import java.io.File;
import java.util.ArrayList;
public class Client
{
public static void main( String[] args )
{
ArrayList<File> fileList = new ArrayList<File>();
fileList.add(new File("D:\\Javafiles\\Javadoc.txt"));
fileList.add(new File("D:\\Javafiles\\Release.txt"));
CompressionContext ctx = null;
ctx = new CompressionContext();
ctx.setCompressionStrategy(new ZipCompressionStrategy());
ctx.createArchive(fileList,"Javafiles");
ctx = new CompressionContext();
ctx.setCompressionStrategy(new RarCompressionStrategy());
ctx.createArchive(fileList,"Javafiles");
}
}
Output
Files are compressed using zip approach: 'Javafiles.zip' file is created
Files are compressed using Rar approach: 'Javafiles.rar' file is created
No comments:
Post a Comment