实现Adapter方式,其实"think in Java"的"类再生"一节中已经提到,有两种方式:组合(composition)和继承(inheritance),
假设我们要打桩,有两种类:方形桩 圆形桩。public class SquarePeg{ public void insert(String str){ System.out.println("SquarePeg insert():"+str); }}public class RoundPeg{ public void insertIntohole(String msg){ System.out.println("RoundPeg insertIntoHole():"+msg);}}现在有一个应用,需要既打方形桩,又打圆形桩。那么我们需要将这两个没有关系的类综合应用,假设RoundPeg我们没有源代码,或源代码我们不想修改,那么我们使用Adapter来实现这个应用:public class PegAdapter extends SquarePeg{ private RoundPeg roundPeg; public PegAdapter(RoundPeg peg)(this.roundPeg=peg;) public void insert(String str){ roundPeg.insertIntoHole(str);}}在上面代码中,RoundPeg属于Adaptee,是被适配者。PegAdapter是Adapter,将Adaptee(被适配者RoundPeg)和Target(目标SquarePeg)进行适配。实际上这是将组合方法(composition)和继承(inheritance)方法综合运用。