设计模式(6、适配器模式)

3个角色:源、适配器、目标
3种形式:
    类适配器-一个源类(1个方法)、一个目标接口(2个方法)、一个适配器(继承源、实现接口);
    对象适配器-一个源类(1个方法)、一个目标接口(2个方法)、一个适配器(组合源、实现接口);
    接口适配器(缺省适配模式)-一个目标接口(多个方法)、一个抽象类(默认空实现所有接口方法)、用的时候new匿名抽象内部类覆盖单独的方法;
例子:springMvc的HandlerAdapter;

类适配器

UML类图:

代码实现:

/**
 * 类适配器,通过继承方式扩展方法,适配接口
 */
//接口-目标
interface Target {
    void method1();

    void method2();
}

//源类
class Adaptee {
    public void method1() {
        System.out.println("method 1");
    }
}

//适配器,继承源类,实现目标
class Adapter extends Adaptee implements Target {
    @Override
    public void method2() {
        System.out.println("method 2");
    }
}

public class ClassAdapter {
    public static void main(String[] args) {
        Target target = new Adapter();
        target.method1();
        target.method2();
    }
}

对象适配器

UML类图:

代码实现:

/**
 * 对象适配器,通过组合方式扩展方法,适配接口
 */
//接口-目标
interface Target {
    void method1();

    void method2();
}

//源类
class Adaptee {
    public void method1() {
        System.out.println("method 1");
    }
}

//适配器,组合源类,实现目标
class Adapter implements Target {
    private Adaptee adaptee;

    public Adapter(Adaptee adaptee) {
        this.adaptee = adaptee;
    }

    @Override
    public void method1() {
        adaptee.method1();
    }

    @Override
    public void method2() {
        System.out.println("method 2");
    }
}

public class ObjectAdapter {
    public static void main(String[] args) {
        Target target = new Adapter(new Adaptee());
        target.method1();
        target.method2();
    }
}

接口适配器(缺省适配模式)

UML类图:

代码实现:

/**
 * 接口适配器,抽象实现方法、用的时候new匿名抽象内部类覆盖单独的方法;
 */
//接口-目标
interface Target {
    void method1();

    void method2();
}

//源类
abstract class Adapter implements Target {
    public void method1() {
        System.out.println("method 1");
    }

    public void method2() {
        System.out.println("method 2");
    }
}

public class InterfaceAdapter {
    public static void main(String[] args) {
        //new匿名抽象内部类覆盖单独的方法;
        Target target = new Adapter() {
            @Override
            public void method2() {
                System.out.println("method 3");
            }
        };
        target.method1();
        target.method2();
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小小绿豆

你的鼓励是我创作最大的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值