适配器模式(Java代码)

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

public class Target {    //这是客户所期望的接口。目标可以是具体的或抽象的类,也可以是接口。
    public void Request()
    {
        System.out.println("普通请求");
    }
}
public class Adaptee {    //需要适配的类
    public void SpecificRequest()
    {
        System.out.println("特殊请求");
    }
}
public class Adapter extends Target{    //通过在内部包装一个Adaptee对象,把源接口转换成目标接口。
    private Adaptee adaptee=new Adaptee();
    public void Request()
    {
        adaptee.SpecificRequest();
    }
}
public class Main {    //客户端代码
    public static void main(String args[])
    {
        Target target1=new Adapter();
        Target target2=new Target();
        target1.Request();
        target2.Request();
    }
}
原文地址:https://www.cnblogs.com/weixiaojun/p/3377607.html