java的适配器模式_java 适配器模式

适配器:基于现有类所提供的服务,向客户提供接口,以满足客户的期望

《Java设计模式》

一、类适配器:

OtherOperation(已存在所需功能的类):

/***@authorcom.tiantian

*@version创建时间:2012-11-21 下午4:39:18*/

public classOtherOperation {public int add(int a, intb){return a +b;

}

}

Operation(为所要实现的功能定义接口):

/***@authorcom.tiantian

*@version创建时间:2012-11-21 下午4:40:12*/

public interfaceOperation {public int add(int a, intb);

}

OperationAdapter(适配器):

/***@authorcom.tiantian

*@version创建时间:2012-11-21 下午4:40:41

* 对象适配器*/

public class OperationAdapter extends OtherOperation implementsOperation{

}

-----------------------------------------------------------------------------------------------------------------------------------

二、对象适配器:

假如客户接口期望的功能不止一个,而是多个。

由于java是不能实现多继承的,所以我们不能通过构建一个适配器,让他来继承所有原以完成我们的期望,这时候怎么办呢?只能用适配器的另一种实现--对象适配器:

符合java提倡的编程思想之一,即尽量使用聚合不要使用继承。

OtherAdd和OtherMinus(已存在功能的两个类):

/***@authorcom.tiantian

*@version创建时间:2012-11-21 下午4:50:14*/

public classOtherAdd {public int add(int a, intb){return a +b;

}

}

/***@authorcom.tiantian

*@version创建时间:2012-11-21 下午4:50:46*/

public classOtherMinus {public int minus(int a, intb){return a -b;

}

}

Operation(为所要实现的功能定义接口):

/***@authorcom.tiantian

*@version创建时间:2012-11-21 下午4:51:59*/

public interfaceOperation {public int add(int a, intb);public int minus(int a, intb);

}

OperationAdapter(通过适配类的对象来获取):

/***@authorcom.tiantian

*@version创建时间:2012-11-21 下午4:52:36*/

public class OperationAdapter implementsOperation{privateOtherAdd otherAdd;privateOtherMinus otherMinus;publicOtherAdd getOtherAdd() {returnotherAdd;

}public voidsetOtherAdd(OtherAdd otherAdd) {this.otherAdd =otherAdd;

}publicOtherMinus getOtherMinus() {returnotherMinus;

}public voidsetOtherMinus(OtherMinus otherMinus) {this.otherMinus =otherMinus;

}

@Overridepublic int add(int a, intb) {returnotherAdd.add(a, b);

}

@Overridepublic int minus(int a, intb) {returnotherMinus.minus(a, b);

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值