适配器模式
适配器模式又分三种:
- 类的适配器模式
- 对象的适配器模式
- 接口的适配器模式
下面我们分明来看下这三种模式是什么,怎么用?
1.类的适配器模式:
核心思想是:当现在有一个类,这个类class1中有一个method1()方法功能,有一个接口interface有method1()方法和method2()方法,如果现在要实现这个interface接口的实现类的具有class1的method1()的方法功能,这个就叫做类的适配。
代码示例:
现在有个电脑类:
public class Computer {
//视频聊天的功能
public void vidioChat() {
System.out.println("this is original method!");
}
}
有一个接口Telephone:
public interface Telephone{
/* 与电脑类中的方法相同 */
public void method1();
/* 新类的方法 */
public void method2();
}
现在要使用一个适配器使Telephone的实现类(手机类)具有Computer 类中的视频聊天的功能
public class Adapter extends Computer implements Telephone{
@Override
public void method2() {
System.out.println("this is the targetable method!");
}
}
Adapter类继承Computer 类,实现Telephone接口,下面是测试代码:
public class AdapterTest {
public static void main(String[] args) {
Telephone telephone1= new Adapter();
telephone1.method1();
telephone1.method2();
}
}
这样Targetable接口的实现类就具有了Computer 类的视频功能。
2.对象的适配器模式
基本思路和类的适配器模式相同,只是将Adapter类作修改,这次不继承Computer类,而是持有Computer类的实例,以达到解决兼容性的问题。修改如下:
public class Adapter implements Telephone{
private Computer cp;
public Adapter (){}
public Adapter (Computer cp){
this.cp=cp
}
@Override
public void method1() {
cp.method1();
}
@Override
public void method2() {
System.out.println("this is the targetable method!");
}
}
测试代码如下:
Computer cp=new Computer ();
Telephone tel=new Adapter (cp);
tel.method1();
使接口实现类和某个对象具备相同的功能,这就是对象适配。
3.接口适配:
接口的适配器是这样的:
有时我们写的一个接口中有多个抽象方法,当我们写该接口的实现类时,必须实现该接口的所有方法,这明显有时比较浪费,因为并不是所有的方法都是我们需要的,有时只需要某一些,此处为了解决这个问题,我们引入了接口的适配器模式,借助于一个抽象类,该抽象类实现了该接口,实现了所有的方法,而我们不和原始的接口打交道,只和该抽象类取得联系,所以我们写一个类,继承该抽象类,重写我们需要的方法就行,如图所示:
现在有有个接口Sourceable :
public interface Sourceable {
public void method1();
public void method2();
}
定义一个抽象类适配器Wrapper2 实现该接口:
public abstract class Wrapper2 implements Sourceable{
public void method1(){}
public void method2(){}
}
定义有个手机类实现接口中的method1()方法:
public class Telephone extends Wrapper2 {
public void method1(){
System.out.println("实现method1方法的功能");
}
}
测试代码:
public class WrapperTest {
public static void main(String[] args) {
Sourceable t1 = new Telephone ();
t1 .method1();
}
}
这样就不需要重写接口中的所有方法了,只需要重写某一个方法。
讲了这么多,总结一下三种适配器模式的应用场景:
类的适配器模式:当希望将一个类转换成满足另一个新接口的类时,可以使用类的适配器模式,创建一个新类,继承原有的类,实现新的接口即可。
对象的适配器模式:当希望将一个对象转换成满足另一个新接口的对象时,可以创建一个Wrapper类,持有原类的一个实例,在Wrapper类的方法中,调用实例的方法就行。
接口的适配器模式:当不希望实现一个接口中所有的方法时,可以创建一个抽象类Wrapper,实现所有方法,我们写别的类的时候,继承抽象类即可。