解決的問(wèn)題
開(kāi)發(fā)了一個(gè)給照片添加濾鏡的功能般甲。假設(shè)需要使用第三方的濾鏡身坐,但是第三方的濾鏡的接口和自己的濾鏡不兼容彬檀,那么就可以使用適配器模式將第三方的濾鏡轉(zhuǎn)換為自己可以用的濾鏡簇秒。
代碼
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()));