适配器模式


1. 类图

image.png

  • Target:客户端需要的功能接口
  • Adaptee:需要被适配的接口
  • Adapter:适配器,将Adaptee适配成客户端需要的Target
  • Client:客户端,调用功能接口Target

2. 示例

2.1 默认适配器

减少子类重写的方法

2.1.1 接口

// 默认适配接口
public interface DefaultAdapter {
    public void testOne();
    public void testTwo();
    public void testThree();
}

2.1.2 默认实现

public class DefaultAdapterImpl implements DefaultAdapter {
    public void testOne() {}
    public void testTwo() {}
    public void testThree() {}
}

2.1.3 目标类

public class Target extends DefaultAdapterImpl {
    @Override
    public void testTwo() {System.out.println("我只需要重写testTwo方法");}
}

2.2 对象适配器

外表为新对象,内部为存在的旧对象

2.2.1 现存的对象

public class Dog {
    public void say(){System.out.println("汪汪汪");}
}

2.2.2 新对象接口

public interface Target {
    void say();
}

2.2.3 新的对象接口实现

public class Cat implements Target {
    private Dog dog;
    public Cat(Dog dog){this.dog = dog;}
    public void say() {
        dog.say();
    }
}

2.2.4 客户端

public class Client {
    public static void main(String[] args) {
        // 创建现存的对象
        Dog dog = new Dog();
        // 传入现存对象,创建新的对象
        Target target = new Cat(dog);
        // 调用新的功能
        target.say();
    }
}

2.3 类适配器

新的类有自己的功能,也有现有的功能

2.3.1 现有的功能

public class Adapteeobj {
    public void run(){System.out.println("我会跑");}
    public void sleep(){System.out.println("我会睡");}
}

2.3.2 需要扩展的功能

public interface AdapteeInter {
    void eat();
}

2.3.3 新的类

public class Adapter extends Adapteeobj implements AdapteeInter {
    public void eat() {System.out.println("我会吃");}
}

2.3.4 客户端

public class Client {
    public static void main(String[] args) {
        Adapter adapter = new Adapter();
        adapter.eat();
        adapter.run();
        adapter.sleep();
    }
}

3. 优点

  • 更好的复用性
    • 复用已经存在的功能来满足客户新的功能
  • 更好的可扩展性
    • 实现适配器功能时,可以调用自己开发的功能

4. 缺点

  • 过多的使用适配器模式,会让系统非常凌乱,不容易整体把握
    • 外部调用的是A接口,内部却是使用B接口来实现功能
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值