适配器模式开发

 Adapter模式也叫适配器模式,是构造型模式之一,经过Adapter模式能够改变已有类(或外部类)的接
口形式。this

在大规模的系统开发过程当中,咱们经常碰到诸如如下这些状况:咱们须要实现某些功能,这些功能已有还不太成熟的一个或多个外部组件,接口

若是咱们本身从新开发这些功能会花费大量时间;因此不少状况下会选择先暂时使用外部组件,开发

之后再考虑随时替换。避免代码大面积修改
Adapter模式就是针对这种相似需求而提出来的。
Adapter模式经过定义一个新的接口(对要实现功能加以抽象),
和一个实现该接口的Adapter(适配器)类来透明地调用外部组件。
这样替换外部组件时,最多只要修改几个Adapter类就能够了,其余
源代码都不会受到影响。class


package com.org.adapter02;
public class Adapter extends Current{
    public void use18V() {
        System.out.println("使用适配器");
        this.use220V();
    }
}static


package com.org.adapter02;
public class Adapter2 {
    private Current current;
    public Adapter2(Current current) {
        this.current = current;
    }
    public void use18V() {
        System.out.println("使用适配器");
        this.current.use220V();
    }
}时间


package com.org.adapter02;
public class Current {
    public void use220V() {
        System.out.println("使用220V电流");
    }
}co

      


public class MainClass {
    public static void main(String[] args) {
//        Current current = new Current();
//        current.use220V();
        
//        Adapter adapter = new Adapter();
//        adapter.use18V();
        
        Adapter2 adapter = new Adapter2(new Current());
        adapter.use18V();
    }
}源代码

相关文章
相关标签/搜索