例子:我的电脑充电器是三插的,但是拖线板只有两头的,解决的办法要么重新买个拖线板,要么买个中间三插的转换下,结果肯定是后面一种,因为后面的便宜。
在java的代码中,典型的应用IO中,里面的FileInputStream就是一个适配器。代码片段如下:
public FileInputStream(File file) throws FileNotFoundException {
String name = (file != null ? file.getPath() : null);
SecurityManager security = System.getSecurityManager();
if (security != null) {
security.checkRead(name);
}
if (name == null) {
throw new NullPointerException();
}
if (file.isInvalid()) {
throw new FileNotFoundException("Invalid file path");
}
fd = new FileDescriptor();
fd.incrementAndGetUseCount();
this.path = name;
open(name);
}
将文件转换为文件流。
突发的例子:杯中的酒,有两种情况,1、被满上 2、喝完
假如,这个杯中的酒就是你的,现在被满上了,但是你不能再喝了,怎么办,只能找人帮忙代酒了,这个时候,就代酒的朋友,就是被适配的对象,来喝完这个杯子中的酒,突发的代码如下:
package com.patten.adaptee;
public interface Cup {
/**
* 倒酒
*/
void pourWine();
/**
*喝酒
*/
void drinkWine();
}
public class MyCup{
public void pourWine() {
System.out.println("不能喝了..,少点..");
}
}
public class Friend extends MyCup implements Cup{
public void drinkWine() {
System.out.println("帮我喝了,谢谢..");
}
}
package com.patten.adaptee;
import junit.framework.TestCase;
public class AppTest extends TestCase{
public void testApp(){
Cup cup = new Friend();
cup.pourWine();
cup.drinkWine();
}
}
将一个类的接口转换成客户希望的另外一个接口,从而使得原本由于接口不兼容而不能一起工作的类可以一起工作

2779

被折叠的 条评论
为什么被折叠?



