设计模式 之 适配器模式

简介

适配器模式, 类似于 平板电脑连接网线, 需要适配器

有两种方式, 一种通过类来继承实现, 另一种通过对象(组合)的方式来实现.

code

public class Computer {
    public void net(NetToUsb adapter) {
        // 上网的具体实现, 找一个转接头
        adapter.handleRequest();
    }

    public static void main(String[] args) {
        Computer c = new Computer();
        Adaptee adaptee = new Adaptee();
        Adapter2 adapter = new Adapter2(adaptee);

        c.net(adapter);
    }
}

// 没有自带上网功能, 但是可以使用插拔的方式进行自带上网功能.
public class Adapter2 implements NetToUsb {
private Adaptee adaptee;

public Adapter2(Adaptee adaptee){
    this.adaptee = adaptee;
}

@Override
public void handleRequest() {
    adaptee.request();
}

}

public interface NetToUsb {
    public void handleRequest();
}

类适配器

// 自带了Adaptee的上网功能
public class Adapter extends Adaptee implements  NetToUsb {
    @Override
    public void handleRequest() {
        super.request(); // 可以上网了
    }
}

public class Adaptee {
    public void request(){
        System.out.println("连写网线上网");
    }
}

UML

Hope is a good thing,maybe the best of things,and no good thing ever dies.----------- Andy Dufresne
原文地址:https://www.cnblogs.com/eat-too-much/p/14819984.html