(9).适配器模式
文章链接:http://chjl2020.iteye.com/blog/262370
适配器:基于现有类所提供的服务,向客户提供接口,以满足客户的期望
过程:
1>客户通过目标接口调用适配器方法对适配器发出请求
2>适配器使用被适配者接口把请求转化成被适配者的一个或多个调用接口
3>客户接收到调用结果,但并未察觉这一切是适配器在起转换作用
1>当需要使用一个现有的类而其接口丌符合你的要求时,就需要使用适配器模式
2>适配器模式将一个对象包装起来改变其接口,装饰者模式将一个对象包装起来增加新的行为戒责仸
3>适配器的意图是将接口转换为丌同的接口
package com.createtype.desginpatterns.adapter;
//用适配器模式:
//以上就是适配器的实现方法之一,类适配器,在以上实现中存在着三中角色分别是:
//2:适配类(原)角色:OtherOperation。
//3:适配器角色:AdapterOperation。
//其中适配器角色是适配器模式的核心。
//适配器的主要工作就是通过封装现有的功能,使他满足需要的接口。
public class AdapterOperation extends OtherOperation implements Operation{
public int add(int a,int b){
return otherAdd(a,b);
}
public int minus(int a, int b) {
// TODO Auto-generated method stub
return 0;
}
public int multiplied(int a, int b) {
// TODO Auto-generated method stub
return 0;
}
}
package com.createtype.desginpatterns.adapter;
//由于java是不能实现多继承的,所以我们不能通过构建一个适配器,
//让他来继承所有原以完成我们的期望,这时候怎么办呢?只能用适配器的另一种实现--对象适配器:
public class AdapterOperation2 implements Operation {
private OtherAdd add;
private OtherMinus minus;
private OtherMultiplied multiplied;
public void setAdd(OtherAdd add) {
this.add = add;
}
public void setMinus(OtherMinus minus) {
this.minus = minus;
}
public void setMultiplied(OtherMultiplied multiplied) {
this.multiplied = multiplied;
}
// 适配加法运算
public int add(int a, int b) {
return add.otherAdd(a, b);
}
// 适配减法运算
public int minus(int a, int b) {
return minus.minus(a, b);
}
// 适配乘法运算
public int multiplied(int a, int b) {
return multiplied.multiplied(a, b);
}
}
package com.createtype.desginpatterns.adapter;
public interface Operation{
public int add(int a,int b);
public int minus(int a,int b);
public int multiplied(int a,int b);
}
package com.createtype.desginpatterns.adapter;
public class OtherAdd{
public int otherAdd(int a,int b){
return a + b;
}
}
package com.createtype.desginpatterns.adapter;
public class OtherMinus{
public int minus(int a,int b){
return a - b;
}
}
package com.createtype.desginpatterns.adapter;
public class OtherMultiplied{
public int multiplied(int a,int b){
return a * b;
}
}
package com.createtype.desginpatterns.adapter;
public class OtherOperation{
public int otherAdd(int a,int b){
return a + b;
}
}