- 结构型设计模式
- 对已经存在的老接口做适配以适应新的需求
今天通过适配器模式来实现三脚插头对两脚的适配
// 使用三角插头进行充电
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