Java面向对象_适配器模式

概念:将一个类的接口转换成客户希望的另外一个接口。适配器模式使得原本由于接口不兼容而不能一起工作的那些类可以一起工作

public class Practice14 {
    
    public static void main(String[] args) {
        // TODO Auto-generated method stub
    PowerA a=new PowerImpl();
    input(a);
    
    PowerB b=new PowerBImpl();
    //input(b);//不能直接用input方法,因为这个方法只接收PowerA接口
    PowerAdapter adapter=new PowerAdapter(b);
    input(adapter);
    
}
    public static void input(PowerA b){
        b.connect();
    }
}
//适配器,可以适配电源A
class PowerAdapter implements PowerA{
    public PowerAdapter(PowerB b){
        this.b=b;
    }
    private PowerB b;
    public void connect(){
        b.insert();
    }
}

interface PowerA{
    public void connect();
}

interface PowerB{
    public void insert();
}

class PowerImpl implements PowerA{
    public void connect(){
        System.out.println("电源A接口正常工作");
    }
}

class PowerBImpl implements PowerB{
    public void insert(){
        System.out.println("电源B接口正常工作");
    }
}
原文地址:https://www.cnblogs.com/shenhainixin/p/5072440.html