Adapter模式--详解

Adapter模式,就是适配器模式,使两个原本没有关联的类结合一起使用。
平时我们会经常碰到这样的情况,有了两个现成的类,它们之间没有什么联系,但是我们现在既想用其中一个类的方法,
同时也想用另外一个类的方法。有一个解决方法是,修改它们各自的接口,但是这是我们最不愿意看到的。这个时候Adapter模式就会派上用场了。
Adapter模式有两种方式,一种是对象适配器,一种是类适配器。
1.对象适配器
假如有两个类,一个是DrawCircle,另一个是DrawRectangle。
public class DrawCircle {
public void draw(String msg){
System.out.println("Draw Circle: " + msg);
}
}
public class DrawRectangle {
public void draw(String msg){
System.out.println("Draw Rectangle: " + msg);
}
}
现在我们有个应用想既可以画圆,又可以画方型,那么我们就需要把这两个类联合起来使用,但是又不想修改各自的接口,
这时就需要Adapter来实现这个应用了。
public class DrawAdapter extends DrawCircle{
private DrawRectangle drawRectangle;
public DrawAdapter(DrawRectangle drawRectangle){
this.drawRectangle = drawRectangle;
}

public void draw(String msg){
drawRectangle.draw(msg);
}
}
这个示例中,DrawAdapter是适配器,DrawRectangle属于Adaptee,是被适配者,适配器将被适配者和适配目标(DrawCircle)进行适配。
具体调用:
DrawCircle drawCircle = new DrawCircle();
drawCircle.draw("DrawCircle"); //display "Draw Circle: DrawCircle"
drawCircle = new DrawAdapter(new DrawRectangle());
drawCircle.draw("DrawRectangle"); //display "Draw DrawRectangle: DrawRectangle"
2.类适配器
上例DrawAdapter继承了DrawCircle,也可以继承DrawRectangle,可是java不支持多重继承,所以其中有个类要实现接口。
还是以上边例子为例:
public interface IDrawCircle {
void draw(String msg);
}
public class DrawCircle implements IDrawCircle {
public void draw(String msg){
System.out.println("Draw Circle: " + msg);
}
}
public class DrawAdapter extends DrawRectangle implements IDrawCircle {

private DrawCircle drawCircle;

public DrawAdapter(DrawCircle drawCircle){
this.drawCircle = drawCircle;
}

public void insert(String msg){
drawCircle.draw(msg);
}
}
【Adapter模式--详解】使用:
DrawRectangle drawRectangle = new DrawRectangle();
drawRectangle.draw("DrawRectangle");

drawRectangle = new DrawAdapter(new DrawCircle());
drawRectangle.draw("DrawCircle");

    推荐阅读