Adapter(适配器模式)

Adapter设计模式的主要思想是将一个类的接口转换成另外一个接口,使得原本由于接口不兼容而不能一起工作的那些类可以一起工作。主要就是起一个转换器的作用,目的就是复用原来的功能,说白了就是让两个接口匹配起来。

应用场景

该模式的应用场景太多了,很多需要的功能模块的接口和我们需要的不完全一致或者有多余或不足,但是需要和我们的系统协同工作,通过Adapter把它包装一下就能使它接口兼容了。平时我们会经常碰到这样的情况,有了两个现成的类,它们之间没有什么联系,但是我们现在既想用其中一个类的方法,同时也想用另外一个类的方法。有一个解决方法是,修改它们各自的接口,但是这是我们最不愿意看到的。这个时候Adapter模式就会派上用场了。

结构模式

实现Adapter适配器设计模式有两种方式:组合(对象适配器模式)和继承(类适配器模式)。

其中对象适配器模式使用组合,UML图如下:

类适配器模式使用继承,UML图如下:

Adapter适配器设计模式中有3个重要角色:被适配者Adaptee,适配器Adapter和目标对象Target。其中两个现存的想要组合到一起的类分别是被适配者Adaptee和目标对象Target角色,我们需要创建一个适配器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)进行适配。
具体调用:

public class Client {
	public static void main(String []args){
		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);
 }
}

使用:

public class Client{
public static void main(String[]args){
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、付费专栏及课程。

余额充值