举一个比较贴近生活的例子,我们买iPad,港货和国货的差别之一就是充电器的接口不一样。因为港货用的是三角插孔,而大陆用的是二孔的,因此就需要一个充电器适配器来转换。但是不管是二孔还是三孔,其目的都是给iPad充电,完成的功能是一样的。可以理解为适配器的功能是将接口(二孔)转换成实际所需要的(三孔)。
假设现在有篮球和足球两个接口,分别实现了一个实例类。现在想打篮球,但是想用足球打,怎么办?
首先我们先定义两个接口以及各自的实现类:
BasketBall.java
public interface BasketBall {
void play();
}
Spalding.java
public class Spalding implements BasketBall{
@Override
public void play() {
System.out.println("Play with hand.");
}
}
Football.java
public interface Football {
public void shoot();
}
MyFootBall.java
public class MyFootBall implements Football{
@Override
public void shoot() {
System.out.println("Play with foot.");
}
}
为了能实现能将足球当篮球打,我们实现一个适配器,适配器通过集成足球类接口,重写shoot方法,并持有篮球类接口对象。
public class BasketBallAdapter implements Football{
private BasketBall basketBall;
public BasketBallAdapter(BasketBall basketBall) {
this.basketBall = basketBall;
}
@Override
public void shoot() {
basketBall.play();
}
}
测试:
public static void main(String[] args) {
BasketBall basketBall = new Spalding();
BasketBallAdapter adapter = new BasketBallAdapter(basketBall);
adapter.shoot();
}