学习笔记-涉及模式之适配器模式

本文内容源于视频教程,若有侵权,请联系作者删除

一、概念

适配器模式(Adapter Pattern)是指将一个类的接口转换成客户期望的另一个接口,使原本的接口不兼容的类可以一起工作,属于结构型设计模式。

 

二、实现

需求:实现一个变压器,将220V交流电转换成5V直流电

创建220V交流电和5V直流电

1 public class Across220V {
2 
3     public int output220V(){
4         int output = 220;
5         System.out.println("输出交流电"+ output + "V");
6         return output;
7     }
8 }
public class Direct5V {

    public int output5V(){
        int output = 5;
        System.out.println("输出直流电V"+ output + "V");
        return output;
    }
}

创建变压器

 1 public class PowerAdapter {
 2 
 3     private Across220V across220V;
 4 
 5     public PowerAdapter(Across220V across220V) {
 6         this.across220V = across220V;
 7     }
 8 
 9     public int change(){
10         int ac = across220V.output220V();
11         // 变压器
12         int dr = ac/44;
13         System.out.println("输入电压" + ac + "V,输出电压" + dr + "V");
14         return ac;
15     }
16 }

测试类

1 public class AdapterTest {
2 
3     public static void main(String[] args) {
4         Across220V across220V = new Across220V();
5         PowerAdapter powerAdapter = new PowerAdapter(across220V);
6         powerAdapter.change();
7     }
8 }

输出

输出交流电220V
输入电压220V,输出电压5V

顾名思义,适配器模式的主要功能是适配,当参数与接口无法匹配时可以通过适配器解决。

当然,适配器模式的应用远不止如此简单,这里只是能让读者简单理解什么是适配器模式。

适配器模式不是设计阶段考虑的设计模式,而是为了弥补设计之初的缺陷。

posted @ 2020-08-15 17:30  落雨有清·风  阅读(89)  评论(0编辑  收藏  举报