读书笔记之设计模式(适配器模式)

来源:互联网 发布:软件学校 编辑:程序博客网 时间:2024/06/02 07:53

适配器模式

适配器模式把一个类的接口变换成客户端所期待的另一种接口,从而使原本因接口不匹配而无法在一起工作的两个类能够在一起工作。

适配器模式又可以分为:
- 类适配器
- 对象适配器

类适配器

主要就是为某一个类而实现适配的一种模式, 把适配的类的API转换成为目标类的API。
- 目标(Target)角色:客户所期待的接口
- 需要被适配的类(Adaptee):需要适配的类
- 适配器(Adaper)角色:把原接口转换成目标接口

代码示例

目标接口
public interface Target{    public void request();}
需要被适配的类
public class Adaptee {    public void specialRequest(){        System.out.println("这是特殊请求!");     }}
适配器
public class Adapter extends Adaptee implements Target{    @Override    public void request(){        this.specialRequest();    }}
测试类
public class TestClient {    public static void main(String[] args) {          // 使用特殊功能类,即适配类          Target adapter = new Adapter();          adapter.request();      } }

因为Java是单继承的,所以这个适配器只能为Adaptee这个类服务,故称为类适配器。

对象适配器

与类适配器模式不同,对象适配器模式不是使用继承关系连接到Adaptee类,而是使用委派关系连接到Adaptee类。

代码示例

public interface Target{    public void request();}
需要被适配的类
public class Adaptee{    public void specialRequest(){        System.out.println("这是特殊请求!");     }}
适配器
public class Adapter implements Target{    // 直接关联被适配类    private Adaptee adaptee;    public Adapter() {        this.adaptee = new Adaptee();    }    @Override    public void request() {        adaptee.specialRequest();    }}

测试类

public class TestClient {    public static void main(String[] args) {          // 使用特殊功能类,即适配类          Target adapter = new Adapter();           adapter.request();    } }
0 0
原创粉丝点击