JAVA中的设计模式研究系列(二)--Adapter(适配器)模式
适配器模式属于接口模式,在JAVA中起始是比较多见的。
在有些项目中,客户可能已经将一些基础的功能接口给我们了,而我们又不能修改它的源代码,只能利用他的接口。那么我们怎么样将客户的功能接口和我们拥有的代码结合起来,以适应于当前项目呢?我们可以这样做:使用Adapter,在这两种接口之间创建一个子接口,既继承了两个父类(或称为父母)的特性和功能,又是他可以很好地使用本项目的需求,这样不是很好吗!
至于如何实现适配器,就要用到组合(composition)和继承(inheritance)了.
详细实现我查了下,网上已经有很多了,比较有代表性的是JDON上的一篇文章,这里我引用下。
假设我们要打桩,有两种类:方形桩 圆形桩.
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);}}public class PegAdapter extends SquarePeg{ private RoundPeg roundPeg; public PegAdapter(RoundPeg peg)(this.roundPeg=peg;) public void insert(String str){super.insert(str); roundPeg.insertIntoHole(str);}}public interface IRoundPeg{ public void insertIntoHole(String msg);}public interface ISquarePeg{ public void insert(String str);}public class SquarePeg implements ISquarePeg{ public void insert(String str){ System.out.println("SquarePeg insert():"+str); }}public class RoundPeg implements IRoundPeg{ public void insertIntohole(String msg){ System.out.println("RoundPeg insertIntoHole():"+msg); }}public class PegAdapter implements IRoundPeg,ISquarePeg{ private RoundPeg roundPeg; private SquarePeg squarePeg; // 构造方法 public PegAdapter(RoundPeg peg){this.roundPeg=peg;} // 构造方法 public PegAdapter(SquarePeg peg)(this.squarePeg=peg;) public void insert(String str){ roundPeg.insertIntoHole(str);}}