这次来看下适配器模式,先来看下Head First中的定义:将一个类的接口,转换成客户期望的另一个接口。适配器让原本接口不兼容的类可以合作无间。
在来看下类图:

再来看下代码吧:
public interface Meat {
void tasteMeat();
}
public class Pork implements Meat {
@Override
public void tasteMeat() {
System.out.println("这是猪肉");
}
}
public interface Vegetables {
void tasteVegetables();
}
public class GreenVegetables implements Vegetables {
@Override
public void tasteVegetables() {
System.out.println("这是青菜");
}
}
public class VegetablesAdapter implements Meat {
private Vegetables vegetables;
public VegetablesAdapter(Vegetables vegetables) {
this.vegetables = vegetables;
}
@Override
public void tasteMeat() {
vegetables.tasteVegetables();
}
}
原文:https://www.cnblogs.com/shenqiaqia/p/11108261.html