Java设计模式之:适配器模式

这里说两种适配器模式

1、类适配模式

在地球时代,所有坐骑都是只能跑,不能飞的,而现在很多坐骑在地球都可以飞了。假设,地球时代的坐骑只能跑,而现在的坐骑不仅能飞还能跑,我们可以用类适配模式来实现,要点是,适配器继承源类,实现目标接口:

 
  1. package adapter;
  2. /**
  3. * DOC 源
  4. *
  5. */
  6. public class Sources {
  7. public void run() {
  8. System.out.println("run");
  9. }
  10. }
 
  1. package adapter;
  2. /**
  3. * DOC 目标接口
  4. *
  5. */
  6. public interface ITarget {
  7. public void run();
  8. public void fly();
  9. }
 
  1. package adapter;
  2. /**
  3. * DOC 继承源类,实现目标接口,从而实现类到接口的适配
  4. *
  5. */
  6. public class Adapter extends Sources implements ITarget {
  7. @Override
  8. public void fly() {
  9. System.out.println("fly");
  10. }
  11. }

2、对象适配模式

假设一个适配器要适配多个对象,可以将这些对象引入到适配器里,然后通过调用这些对象的方法即可:

 
  1. package adapter;
  2. /**
  3. *
  4. * DOC 源对象,只有跑的功能
  5. *
  6. */
  7. public class Animal {
  8. public void run() {
  9. System.out.println("run");
  10. }
  11. }
 
  1. package adapter;
  2. /**
  3. * DOC 目标接口,既能跑,又能飞
  4. *
  5. */
  6. public interface ITarget {
  7. public void run();
  8. public void fly();
  9. }
 
  1. package adapter;
  2. /**
  3. * DOC 通过构造函数引入了源对象,并实现了目标的方法
  4. *
  5. */
  6. public class Adapter implements ITarget {
  7. private Animal animal;
  8. // private animal animal2....可以适配多个对象
  9. public Adapter(Animal animal) {
  10. this.animal = animal;
  11. }
  12. /**
  13. * DOC 拓展接口要求的新方法
  14. */
  15. public void fly() {
  16. System.out.println("fly");
  17. }
  18. /**
  19. * DOC 使用源对象的方法
  20. */
  21. public void run() {
  22. this.animal.run();
  23. }
  24. }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值