适配器模式(Adapter)
在软件系统中,由于应用环境的变化,常常需要将“一些存在的对象” 放在新的环境中应用,但是这些现存对象不满足新环境要求的接口。为了能利用现有对象的良好实现,同时又能满足新的应用环境所要求的接口,采用适配器模式。
适配器模式:把一个类的接口变成客户端所期待的另一种接口,从而使原本接口不匹配而无法在一起工作的两个类能够在一起工作。
适配器adapter
适配者adaptee :需要适配的类
- 类适配器模式:适配器与适配者之间是继承关系
- 对象适配器模式:适配器与适配者之间是关联关系
主要是对象适配者模式
class Target//客户所期待的接口,目标可以是具体的或抽象的类,也可以是接口
{
public void Request()
{
System.out.println("普通请求");
}
}
class Adaptee
{
public void specificRequest()
{
System.out.println("特殊请求");
}
}
class Adapter extends Target
{
private Adaptee adaptee=new Adaptee();
public void Request()
{
//把调用Request()方法变成调用SpecificRequest()方法
adaptee.specificRequest();
}
}
public class main
{
public static void main(String[] args) {
Target target=new Adapter();
target.Request();
}
}
类的Adapter模式示意性实现
interface ITarget
{
void Request();
}
class Adaptee
{
public void specificRequest()
{
System.out.println("特殊请求");
}
}
class Adapter extends Adaptee implements ITarget
{
public void Request()
{
//把调用Request()方法变成调用SpecificRequest()方法
this.specificRequest();
}
}
public class main
{
public static void main(String[] args) {
ITarget t=new Adapter();
t.Request();
}
}
- 适配器模式主要应用于“希望复用一些现存的类,但是接口又与复用环境要求不一致的情况”,在遗留代码复用,类库迁移等方面非常有用。
- 适配器模式有对象适配器和类适配器两种形式的实现结构
- 类适配器采用“多继承”的实现方式,具有不良的高耦合
- 对象适配器采用“对象组合或关联”的方式,更符合松耦合精神。
使用情况:系统需要使用这个现有的类,但此类的接口不符合系统的需要
优点:
- 更好的复用性
- 可拓展性
缺点: - 过多使用适配器,会让系统非常凌乱
本质:转换匹配,复用功能