菜鸟硕枫设计模式系列之7 适配器模式

适配器模式,正如适配器这个名字一样,起一个转换的作用。目的是通过接口转化,使得新系统和老系统可以正常交互。适配器模式是一种结构型模式。

适配器模式类图:
[img]http://dl.iteye.com/upload/attachment/364532/87dc220e-6d9c-34b2-9864-bed07b82adcf.jpg[/img]

具体实现demo:
新系统:

package adapterPattern;

public interface NewSystem {

public void doAnotherthing(String input);
}


实现:

package adapterPattern;

public class NewSystemImpl implements NewSystem{


public void doAnotherthing(String input) {
System.out.println("接口参数转换后,我能使用了哈");

}

}


老系统:

package adapterPattern;

public interface OldSystem {

public int doSomething();
}


实现:

package adapterPattern;

public class OldSystemImpl implements OldSystem{

public int doSomething() {
System.out.println("我只能返回整型值");
return 0;
}

}


适配器类:

package adapterPattern;

public class Adapter {

public String convertMethod(int input){
return Integer.toString(input);
}
}


测试类:

package adapterPattern;

public class AdapterPatternTest{

public static void main(String[] args){

OldSystemImpl oldSystem = new OldSystemImpl();

NewSystemImpl newSystemImpl = new NewSystemImpl();

Adapter adapter = new Adapter();

newSystemImpl.doAnotherthing(adapter.convertMethod(oldSystem
.doSomething()));
}
}


说明:老系统参数为int ,新系统接收输入为string,接口不匹配,通过adapter的转化之后,使得新老系统可以交互了。另外,jdk 1.6中 Runable task 转成 Callable task就是一个典型的适配器模式,其中 RunnableAdapter这个类就是适配器。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值