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);
 }

}

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值