设计模式 - 适配器模式

来源:互联网 发布:免费淘宝开店教程视频 编辑:程序博客网 时间:2024/05/18 13:04

什么是适配器模式?

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

的两个类能够在一起工作。


设配器模式的结构

源(Adapee)角色:现有的需要适配的接口。

适配器(Adaper)角色:适配器类是适配器模式的核心,适配器把源接口转换成目标接口。

目标(Target)角色:所期待得到的接口。


适配器模式有类适配器模式对象适配器模式两种不同的形式。

类适配器模式


/** 源 **/public class Adapee{    public void fun1(){};}/** 目标 **/public interface Target {    public void fun1();     public void fun2(); }


/** 适配器类 **/public class Adapter extends Adaptee implements Target {    @Override    public void fun2() {        ......     }}


对象适配器模式

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

public class Adapter {    private Adaptee adaptee;    public Adapter(Adaptee adaptee){        this.adaptee = adaptee;    }    public void fun1(){        this.adaptee.fun1();    }    public void fun2(){        ......    }}



0 0