一、定义:将一个类的接口变成另一个客户端所期待的另一种接口,从而使原本因接口不匹配二无法在一起的工作能够在一起工作。Convert the interface of a class into another interface clients expect. Adapter lets classes work together that couldn't otherwise because of incompatible interfaces.
二、简单代码示例
定义源接口和目标接口
public interface Source {
void printNameAndSex(); //源接口答应名字和性别
}
public interface Target {
void printNameAndAge(); //目标接口答应名字和年龄
}
源接口的实现类
public class Object1 implements Source {
public User user;
public Object1(User user) {
this.user = user;
}
@Override
public void printNameAndSex() {
// TODO Auto-generated method stub
System.out.println("Name=" + user.getName() + " Sex=" + user.getSex());
}
}
利用源接口的实现类去实现目标接口
public class Adaptor extends Object1 implements Target {
public Adaptor(User user) {
super(user);
// TODO Auto-generated constructor stub
this.user = user;
}
@Override
public void printNameAndAge() {
// TODO Auto-generated method stub
System.out.println("Name=" + user.getName() + " Age=" + user.getAge());
}
}
Name=小明 Sex=mail
Convert to target interface
Name=小明 Age=10
很明显适配器的作用就是将一个接口的实现类,以另一种接口的方式发布。其中要保证源接口中由足够的数据,能够得到目标接口要输出的数据,可以通过数据计算或者变换而来,总之源接口中一定要包含目标接口需要的数据信息,只是形式不同,如果不包含则适配器将没有效果。
适配器将两个没有关联的类在一起运行,增加了类的透明性,不用修改接口,就能以新接口形式发布,提高了类的复用。灵活性好,适配器直接删除不影响源类的使用。
适配器适用于正在服役的项目的扩展,如建立企业服务总线ESB等系统时。