解决的问题
开发一个保存图片的功能,保存图片前,需要先对图片进行压缩、添加滤镜等处理。
代码
Compressor
:
package com.cong.designpattern.strategy;
public interface Compressor {
public void compress(String fileName);
}
JpegCompressor
:
package com.cong.designpattern.strategy;
public class JpegCompressor implements Compressor{
@Override
public void compress(String fileName) {
System.out.println("Compress to Jpeg");
}
}
PngCompressor
:
package com.cong.designpattern.strategy;
public class PngCompressor implements Compressor{
@Override
public void compress(String fileName) {
System.out.println("Compress to PNG");
}
}
Filter
:
package com.cong.designpattern.strategy;
public interface Filter {
public void filter(String fileName);
}
BlackAndWhiteFilter
:
package com.cong.designpattern.strategy;
public class BlackAndWhiteFilter implements Filter{
@Override
public void filter(String fileName) {
System.out.println("Filter with black and white");
}
}
ImageStore
:
package com.cong.designpattern.strategy;
public class ImageStore {
public ImageStore(Compressor compressor, Filter filter) {
this.compressor = compressor;
this.filter = filter;
}
private Compressor compressor;
private Filter filter;
public void store(String fileName) {
compressor.compress(fileName);
filter.filter(fileName);
}
}
Test code:
ImageStore imageStore = new ImageStore(new PngCompressor(), new BlackAndWhiteFilter());
imageStore.store("a");
UML
好处
满足单一职责原则。ImageStore
应该只有保存图片的职责,通过组合的方式把压缩图片、添加滤镜等操作封装到其他相应的类。
Strategy Pattern和State Pattern非常像,原理是一样的。可以理解为State Pattern是只有一种Strategy的Strategy Pattern。