什么是适配器模式?

    1. 将一个类的接口转换成客户希望的另外一个接口,Adapter模式使得原本由于接口不兼容而不能一起工作的那些累可以在一起工作

    模式中的角色

    1. 目标接口(target):客户锁期待的接口,目标可以是具体的或抽象的类,也可以是接口
    2. 需要适配的类(Adaptee):需要适配的类或适配者类
    3. 适配器(Adapter):通过包装一个需要适配的对象,把原接口转换成目标接口

    应用场景

    1. 1.经常用来做旧系统改造和升级
    2. 2.如果我们的系统开发之后再也不需要维护,那么很多模式都是没有必要的,但是不幸的是,事实却是维护一个系统的代价往往是开发一个系统的数倍
    3. 例子:
    4. java.io.InputStreamReader(InputStream)
    5. java.io.OutputStreamWrite(OutputStream)

    代码

    需要适配的对象

    1. package factorymode.simplefactory.adapter;
    2. public interface SmallPort {
    3. // 需要适配的接口
    4. public void userSmallPort();
    5. }

    适配器接口

    1. package factorymode.simplefactory.adapter;
    2. public interface BigPort {
    3. // 希望使用的接口
    4. public void userBigPort();
    5. }

    适配器

    1. package factorymode.simplefactory.adapter;
    2. public class SmallToBig implements BigPort {
    3. private SmallPort smallPort;
    4. public SmallToBig(SmallPort smallPort) {
    5. this.smallPort = smallPort;
    6. }
    7. @Override
    8. public void userBigPort() {
    9. this.smallPort.userSmallPort();
    10. }
    11. }

    客户端

    1. package factorymode.simplefactory.adapter;
    2. public class Client {
    3. public static void main(String[] args) {
    4. SmallPort smallPort = new SmallPort() {
    5. @Override
    6. public void userSmallPort() {
    7. System.out.println("使用小口");
    8. }
    9. };
    10. BigPort bigPort = new SmallToBig(smallPort);
    11. bigPort.userBigPort();
    12. }
    13. }