Skip to content

Latest commit

 

History

History
81 lines (66 loc) · 1.46 KB

Adapter.md

File metadata and controls

81 lines (66 loc) · 1.46 KB

介绍

  • 结构型设计模式
  • 对已经存在的老接口做适配以适应新的需求

今天通过适配器模式来实现三脚插头对两脚的适配

目标接口

// 使用三角插头进行充电
public interface ThreePinPlug {

    void charge();
}

适配器

public class TwoPinPlugAdapter implements ThreePinPlug {

    private TwoPinPlug plug;

    public TwoPinPlugAdapter() {
        this.plug = new TwoPinPlug();
    }

    @Override
    public void charge() {
        plug.charge();
    }
}

需要适配的类

public class TwoPinPlug {

    public void charge() {
        System.out.println("Is charging");
    }
}

客户端

public class User {
    // 使用三脚插头充电,做适配
    private ThreePinPlug plug;

    public User(ThreePinPlug plug) {
        this.plug = plug;
    }

    public void setPlug(ThreePinPlug plug) {
        this.plug = plug;
    }

    public void charge() {
        plug.charge();
    }
}
// 测试类
public class Main {

    public static void main(String[] args) {
        User user = new User(new TwoPinPlugAdapter());
        user.charge();
    }
}
// 测试结果
Is charging