设计模式之适配器模式

来源:互联网 发布:淘宝欧舒丹是正品吗 编辑:程序博客网 时间:2024/06/06 02:15

接口或方法不兼容的时候,中间添加一个适配器用来间接调用目标方法。

假设我们现在有一个Normal类

class Normal {    public void action() {        System.out.println("normal action");    }}

测试类已有的一个方法要求传入Normal类对象

public class Test {    public static void act(Normal target) {        target.action();    }}

这时候我们有个Special类也想要兼容这个方法

class Special {    public void action() {        System.out.println("special action");    }}

于是就可以创建一个Normal类的子类适配器Adapter,把Special类封装在Adapter里面,这样Adapter就符合方法调用的要求,而实际调用的是Special类的方法。

class Adapter extends Normal {    private Special special;    public Adapter(Special adaptee) {        this.special = adaptee;    }    @Override    public void action() {        special.action();    }}

测试类:

public class Test {    public static void act(Normal target) {        target.action();    }    public static void main(String[] args) {        act(new Normal());        act(new Adapter(new Special()));    }}

输出结果:

normal actionspecial action

适配器模式可以用在接口方法不兼容的地方,或者说希望提高兼容性。