适配器模式

例子:我的电脑充电器是三插的,但是拖线板只有两头的,解决的办法要么重新买个拖线板,要么买个中间三插的转换下,结果肯定是后面一种,因为后面的便宜。

在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();
}


package com.patten.adaptee;


public class MyCup{


public void pourWine() {
System.out.println("不能喝了..,少点..");
}


}

package com.patten.adaptee;


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();
}
}


备注:

将一个类的接口转换成客户希望的另外一个接口,从而使得原本由于接口不兼容而不能一起工作的类可以一起工作

转载于:https://my.oschina.net/kcnf/blog/309852

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值