解决的问题
开发了一个给照片添加滤镜的功能。假设需要使用第三方的滤镜,但是第三方的滤镜的接口和自己的滤镜不兼容,那么就可以使用适配器模式将第三方的滤镜转换为自己可以用的滤镜。
代码
Filter
:
package com.cong.designpattern.adapter;
public interface Filter {
public void apply(Image image);
}
AvaFilter
:
package com.cong.designpattern.adapter;
public class AvaFilter implements Filter {
@Override
public void apply(Image image) {
System.out.println("Apply ava filter");
}
}
Image
:
package com.cong.designpattern.adapter;
public class Image {
}
ImageView
:
package com.cong.designpattern.adapter;
public class ImageView {
private Image image;
public ImageView(Image image) {
this.image = image;
}
public void applyFilter(Filter filter) {
filter.apply(this.image);
}
}
第三方滤镜BavaFilter
:
package com.cong.designpattern.adapter.thirdParty;
import com.cong.designpattern.adapter.Image;
public class BavaFilter {
public void init() {}
public void render(Image image) {
System.out.println("Apply bava filter");
}
}
适配器BavaFilerAdapter
:
package com.cong.designpattern.adapter;
import com.cong.designpattern.adapter.thirdParty.BavaFilter;
public class BavaFilerAdapter implements Filter {
private BavaFilter bavaFilter;
public BavaFilerAdapter(BavaFilter bavaFilter) {
this.bavaFilter = bavaFilter;
}
@Override
public void apply(Image image) {
this.bavaFilter.init();
this.bavaFilter.render(image);
}
}
Test code:
ImageView imageView = new ImageView(new com.cong.designpattern.adapter.Image());
imageView.applyFilter(new AvaFilter());
imageView.applyFilter(new BavaFilerAdapter(new BavaFilter()));
网友评论