您的位置:首页 > 其它

适配器模式

2018-02-04 17:09 190 查看
适配器模式将某个类的接口转换成客户端期望的另一个接口表示。核心是有一个Source类,拥有一个方法待适配,目标接口是 Targetable ,通过 Adapter 类,将Source 的功能扩展到 Targetable 里。主要包括三类:类适配器,对象适配器,接口适配器。常见的应用场景:java.io.InputstreamReader(InputStream)

public class Source {

public void method1(){
System.out.println("this is the original method");
}
}


public interface Targetable {
//与原类中的方法相同
void method1();
//新类的方法
void method2();
}


类适配器

//继承Source,实现Targetable
public class Adapter extends Source implements Targetable {
@Override
public void method2() {
System.out.println("this is the targetble method");
}
}


对象适配器

public class Wrapper implements Targetable{
//持有Source对象
private Source source;

public Wrapper(Source source) {
this.source = source;
}

@Override
public void method1() {
source.method1();
}

@Override
public void method2() {
System.out.println("this is the targetable method");
}
}


public cla
4000
ss Test {

public static void main(String[] args) {
//调用类适配器
classAdapter();
//调用对象适配器
objectAdapter();
}

public static void classAdapter(){
Targetable target = new Adapter();
target.method1();
target.method2();
}

public static void objectAdapter(){
Wrapper wrapper = new Wrapper(new Source());
wrapper.method1();
wrapper.method2();
}
}


结果输出如下:

this is the original method

this is the targetble method

this is the original method

this is the targetable method

上面只有类的适配器和对象适配器的例子,接口适配器也比较简单,就是一个接口可能有多个抽象方法,我们实现接口的时候,有些并不需要,但是仍要实现,就会造成浪费,现在引入一个抽象类,实现该接口,我们的类继承这个抽象类,只需要重写我们需要的方法就可以了。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: