适配器模式包括类适配器模式和对象适配器模式
(1)类适配器模式
典型的类适配器模式代码
public class Adapter extends Adaptee implements Target{
public void request(){ //实现Target的request抽象方法并调用适配者中客户需要的方法
super.specificRequest();
}
}
实例说明:需要设计一个可以模拟各种动物行为的机器人,在机器人中定义了一系列方法,如机器人叫喊方法cry()、机器人移动方法move()等。如果希望在不修改已有代码的基础上使机器人能像狗一样叫,像狗一样跑,可以使用适配器模式进行系统设计
(1)目标抽象类Robot(机器人接口)
public interface Robot{
public void cry();
public void move();
}
Robot充当目标抽象类,客户端针对抽象的Robot类进行编程,在Robot中声明了客户端要调用的业务方法(也可以是实现)
(2)适配者类Dog(Dog类)
public class Dog{
public void wang(){
System.out.println("狗汪汪叫");
}
public void run(){
System.out.println("狗狗快跑");
}
}
适配者Dog类是一个现有的具体类,它包含了用户所需业务方法的具体实现,如本类中的wang()方法和run()方法,但是方法名和Target接口不一致,甚至没有Target的源代码。
(3)适配器类DogAdapter类
public class DogAdapter extends Dog implements Robot{
public void cry(){
System.out.print("机器人模仿:");
super.wang();
}
public void move(){
System.out.print("机器人模仿:");
super.run();
}
}
在类适配器中,它实现了Target接口,实现了里面声明的抽象业务方法,并继承Adaptee类,为了调用适配者类的业务方法
如果要使用其他的适配者,直接新增加一个适配器类即可,不用修改代码
(2)对象适配器模式
对象适配器模式典型的代码
public calss Adapter extends Target{
private Adapter adaptee; //定义一个私有的适配者实例
public Adapter(Adapter adaptee){ //,通过构造注入的方法注入一个适配者的实例
this.adapter = adaptee;
}
public void request(){ //在适配器的request()方法中用适配者调用客户需要的方法
adaptee.specificRquest();
}
}