适配器模式

适配器模式的组成:
1) 目标(Target)角色:定义Client 使用的接口。
2) 被适配(Adaptee)角色:这个角色有一个已存在并使用了的接口,而这个接口是需要我们
适配的。
3) 适配器(Adapter)角色:这个适配器模式的核心。它将被适配角色已有的接口转换为目标
角色希望的接口。

 

适配器模式和代理模式主要区别在于:代理模式是不改变接口命名的;而适配器模式则强调接口转换。

 

更深入的讲解请见:http://www.iteye.com/topic/262370

 

客户端接口:

Java代码   收藏代码
  1. public interface Operation{  
  2.       public int add(int a,int b);  
  3.       public int minus(int a,int b);  
  4.       public int multiplied(int a,int b);  
  5. }  

 

 被适配角色:

Java代码   收藏代码
  1. public class OtherAdd{  
  2.       public int otherAdd(int a,int b){  
  3.            return a + b;  
  4.       }  
  5. }  
  6.   
  7. public class OtherMinus{  
  8.       public int minus(int a,int b){  
  9.            return a - b;  
  10.       }  
  11. }  
  12.   
  13. public class OtherMultiplied{  
  14.       public int multiplied(int a,int b){  
  15.            return a * b;  
  16.       }  
  17. }  

 

适配器角色:

Java代码   收藏代码
  1. public class AdapterOperation implements Operation{  
  2.       private OtherAdd add;  
  3.       private OtherMinus minus;  
  4.       private OtherMultiplied multiplied;  
  5.   
  6.       public void setAdd(OtherAdd add){  
  7.             this.add = add;  
  8.       }  
  9.   
  10.       public void setMinus(OtherMinus minus){  
  11.             this.minus = minus;  
  12.       }  
  13.   
  14.       public void setMultiplied(OtherMultiplied multiplied){  
  15.             this.multiplied = multiplied;  
  16.       }  
  17.   
  18.       //适配加法运算  
  19.       public int add(int a,int b){  
  20.            return add.otherAdd(a,b);  
  21.       }  
  22.   
  23.       //适配减法运算  
  24.       public int minus(int a,int b){  
  25.           return minus.minus(a,b);  
  26.       }  
  27.   
  28.       //适配乘法运算  
  29.       public int multiplied(int a,int b){  
  30.          return multiplied.multiplied(a,b);  
  31.       }  
  32. }  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值