将一个类的接口转换为客户希望的另外一个接口
适配器分为类适配器模式和对象适配器模式(前者应用较少)
适配器模式中主要包括三个角色:
(1)目标接口 :当前系统业务所期待的接口
(2)适配者类:现存的接口
(3)适配器类:转换器,将适配者接口转化为目标接口
其实是旧的接口希望通过适配器类,实现适配者类中的功能,成为一个新的接口
旧的接口,没有适配者中的功能(只有request方法)
新的接口,有适配者中的功能(千方百计想能够调用specificRequest方法)
1.类适配器模式实现:
//目标接口
interface Target
{
public void request();
}
//适配者类
class Adaptee
{
public void specificRequest()
{
System.out.println("适配者中的业务代码被调用!");
}
}
//适配器类
//适配器类继承适配者类,而且实现目标接口(这意味着适配器类需要实现目标接口里的request方法)
//再加上继承适配者类,所以适配器类中有两个方法:request方法和specificRequest方法
class ClassAdapter extends Adaptee implements Target
{
public void request()
{
specificRequest();
}
}
//客户端代码
public class ClassAdapterTest
{
public static void main(String[] args)
{
System.out.println("类适配器模式测试:");
Target target = new ClassAdapter();
//此时Target接口就不止一个request方法了,而是和适配器类一样也有
//request和specificRequest两个方法了
target.request();
}
}
2.对象适配器模式
Adapter适配器类实现了旧目标接口,所以必须重写request函数
Adapter适配器虽然只有request函数,但是它的request函数里调用了一个适配者类对象的specificRequest方法,所以还是可以调用适配者类中的specificRequest方法
//目标接口
interface Target
{
public void request();
}
//适配者接口
class Adaptee
{
public void specificRequest()
{
System.out.println("适配者中的业务代码被调用!");
}
}
//适配器类
class Adapter implements Target
{
private Adaptee adaptee;
public Adapter(Adaptee adaptee)
{
this.adaptee=adaptee;
}
public void request()
{
adaptee.specificRequest();
}
}
//客户端代码
public class Test
{
public static void main(String[] args)
{
System.out.println("对象适配器模式测试:");
Adaptee adaptee = new Adaptee();
Target target = new Adapter(adaptee);
target.request();
}
}
简洁版:
//目标接口
interface Target
{
public void request();
}
//适配者接口
class Adaptee
{
public void specificRequest()
{
System.out.println("适配者中的业务代码被调用!");
}
}
//适配器类
class Adapter implements Target
{
public void request()
{
核心这句,在request函数里面调用一个适配者类对象的specificRequest方法
adaptee.specificRequest();
}
}
//客户端代码
public class Test
{
public static void main(String[] args)
{
Adaptee adaptee = new Adaptee();
Target target = new Adapter(adaptee);
target.request();
}
}