java 适配器类,在Java中实现类适配器模式

While reading up on the Class Adapter pattern in Head First Design Patterns, I came across this sentence:

class adapter... because you need multiple inheritance to implement it, which is not possible in Java

Just to experiment, I tried the following:

interface MyNeededInterface{

public void operationOne(MyNeededInterface other);

public MyNeededInterface operationTwo();

}

public class ThirdPartyLibraryClass{

public void thirdPartyOp();

}

Suppose I create :

class ThirdPartyWrapper extends ThirdPartyLibraryClass implements MyNeededInterface{

@Override

public void operationOne(ThirdPartyWrapper other){

this.thirdPartyOp();

dosomeExtra();

}

@Override

public ThirdPartyWrapper operationTwo(){

int somevalue = doSomeThingElse();

return new ThirdPartyWrapper(somevalue);

}

}

In my code, I can use:

MyNeededInterface myclass = createThirdPartyWrapper();

myclass.operationOne(someobj);

...

Is this not the Class Adapter pattern?

解决方案

The class adapter pattern is not possible in Java because you can't extend multiple classes. So you'll have to go with the adapter pattern which uses composition rather than inheritance.

An example of the adapter pattern through composition can be found below:

interface Duck

{

public void quack();

}

class BlackDuck implements Duck

{

public void quack() { }

}

class Turkey

{

public void gobble() { }

}

class TurkeyAdapter implements Duck

{

private Turkey t;

public TurkeyAdapter(Turkey t)

{

this.t = t;

}

public void quack()

{

// A turkey is not a duck but, act like one

t.gobble();

}

}

Now you can pass a Turkey to a method which is expecting a Duck through the TurkeyAdapter.

class DuckCatcher

{

public void catch(Duck duck) { }

}

By using the adapter pattern the DuckCatcher is now also able to catch Turkey(Adapter)s and Ducks.

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值