大话设计模式之适配器模式

1:适配器模式类图

 

 

2:适配器模式分析

  客户端client需要实现接口Target的类,但是由于Adaptee没有实现该接口,虽然Adaptee的功能与所需要功能类似,但是就是没有实现该接口,我们该怎么办尼?我们可以重新定义一个新类实现Target接口,同时再新类内部引用一个Adaptee类,我们命名为Adapter类。

  当Adapter类中实现Target接口的方法时,要调用内部引用的Adaptee类,因为我们的目的就是为了使用Adaptee类的功能,给Cilent使用。

3:适配器模式示例代码

  给姚明设计一个适配器,用来帮助姚明听懂英文。使用上面的适配器类图的设计基本原理我们可以完成这个适配器模式的代码

package adapterPattern;

/**
 * @author :dazhu
 * @date :Created in 2020/4/4 11:13
 * @description:
 * @modified By:
 * @version: $
 */
public class Main {
    public static void main(String[]args){
        YaoMing ym = new YaoMing();
        EnglishToChinese etc = new EnglishToChinese(ym);
        etc.speakEnglish();

    }
}
package adapterPattern;

/**
 * @author :dazhu
 * @date :Created in 2020/4/4 11:13
 * @description:
 * @modified By:
 * @version: $
 */
public interface English {
    public void speakEnglish();
}
package adapterPattern;

/**
 * @author :dazhu
 * @date :Created in 2020/4/4 11:13
 * @description:
 * @modified By:
 * @version: $
 */
public class EnglishToChinese implements English{

    YaoMing ym = null;
    public EnglishToChinese(YaoMing ym){
        this.ym = ym;
    }

    @Override
    public void speakEnglish() {
        ym.getIt();
    }
}package adapterPattern;

/**
 * @author :dazhu
 * @date :Created in 2020/4/4 11:13
 * @description:
 * @modified By:
 * @version: $
 */
public class YaoMing {
    public void getIt(){
        System.out.println("我听懂了");
    }
}

 

posted @ 2020-04-04 11:19  大朱123  阅读(223)  评论(0编辑  收藏  举报