打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
设计模式学习笔记-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(){
}

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

public void insert(String msg){

  if (null == drawCircle)
    super.draw(msg);
  else
    drawCircle.draw(msg);

}

}

使用:
DrawRectangle drawRectangle = new DrawRectangle();
drawRectangle.draw("rectangle");

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

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


第二个例子运行结果:

Draw Rectangle: rectangle
Draw Circle: circle
Draw Rectangle: rectangle

本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
9. 适配器模式
设计模式系列 - 桥接模式
I2C 总线(适配器) ,核心, 设备驱动
linux内核I2C体系结构(注意结构体原型)
I2C
linux下S3C2440–I2C驱动学习之四“i2c
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服