设计模式–适配器模式
1.模式定义
适配器模式把一个类的接口变换成客户端所期待的另一种接口,从而使原本接口不匹配而无法在一起工作的两个类能够在一起工作。
2.模式分类:分为类的适配器模式和对象的适配器模式。
3.模式角色
(1).目标角色(target):这是客户所期待的接口。目标可以使具体的或抽象的类。
(2).源角色(adaptee):需要适配的类。
(3).适配器角色(adapter):通过在内部包装的一个adaptee对象,把源接口转换为目标接口。
4.对象适配器模式
package a01;
public interface Target {
public void Request();
}
package a01;
public class Adaptee {
public void SpecificRequest()
{
System.out.println("特殊请求");
}
}
package a01;
public class Adapter implements Target {
private Adaptee adaptee=new Adaptee();
@Override
public void Request() {
// TODO Auto-generated method stub
adaptee.SpecificRequest();
}
}
package a01;
public class Client {
public static void main(String[] args) {
// TODO Auto-generated method stub
Target target=new Adapter();
target.Request();
}
}
5.类适配器模式
package a02;
public interface Target {
public void Request();
}
package a02;
public class Adaptee {
public void SpecificRequest()
{
System.out.println("特殊请求");
}
}
package a02;
public class Adapter extends Adaptee implements Target {
@Override
public void Request() {
// TODO Auto-generated method stub
this.SpecificRequest();
}
}
package a02;
public class Client {
public static void main(String[] args) {
// TODO Auto-generated method stub
Target target=new Adapter();
target.Request();
}
}
7.适配器模式在遗留代码的复用和类库转移等方面非常有用。
- 类适配器采用“多继承”的实现方式,带来了不良的高耦合,所以一般不推荐使用。
- 对象适配器采用“对象组合”的方式,更符合松耦合精神。
8.适配器模式使用情景
- 系统需要使用现有的类,而此类的接口不符合系统的需要。
- 想要建立一个可以重复使用的类,该类可能与其他不相关的类或不可预见的类协同工作。
- 在设计里面,你想使用一个已经存在的子类,但是不可能对每一个子类都进行适配。对象适配器可以适配他们的父类接口。
9.适配器模式的优缺点
-
优点:更好的复用性,更好的扩展性
-
缺点:过多的使用适配器,会让系统非常凌乱,不容易整体进行把握。
10.本质:转换匹配,复用功能。