当前位置:   article > 正文

Java设计模式 - 适配器模式(结构型)_java 适配器设计模式 csdn

java 适配器设计模式 csdn

一、模式定义

        适配器模式:将一个类的接口转换成客户希望的另一个接口。适配器模式让那些接口不兼容的类可以一起工作。

        Adapter Pattern:Convert the interface of a class into another interface clients expect. Adapter lets classes work together that couldn’t otherwise because of incompatible interfaces.

二、模式中包含的角色

        (1)AC2DC(目标抽象类):目标抽象类定义客户所需要的接口,可以是一个抽象类或接口,也可以是具体类。在类适配器中,由于Java语言不支持多重继承,它只能是接口。

        (2)Adapter、Adapter2(适配器类):它可以调用另一个接口,作为一个转换器,对Adaptee和AC2DC进行适配。适配器Adapter/Adapter2是适配器模式的核心,在类适配器中,它通过实现AC2DC接口并继承Adapter类来使二者产生联系,在对象适配器中,它通过继承AC2DC并关联一个Adaptee对象使二者产生联系。

        (3)Adaptee(适配者类):适配者即被适配的角色,它定义了一个已经存在的接口,这个接口需要适配,适配者类一般是一个具体类,包含了客户希望使用的业务方法,在某些情况下甚至没有适配者类的源代码。

三、模式类图

图3-1 适配器模式示例类图

四、模式实现:模拟电脑充电

(1)目标抽象类(AC2DC):

package adapte;
//抽象接口---代表所有类型的充电器(适配器)

public interface AC2DC {
	
	public void handleRequest();
	
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

(2)适配者类(Adaptee):

package adapte;
//适配者类---插座(需要被适配的类)

public class Adaptee {
	
	public void charge() {
		System.out.println("已连接电脑,正在充电ing...");
	}
	
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

(3)适配器类(Adapter):

package adapte;
//适配器类---适配器(电脑充电器)
//继承方式实现-->>类适配器

public class Adapter extends Adaptee implements AC2DC{
	
	//处理用户请求
	public void handleRequest() {
		super.charge();
	}
	
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

(4)适配器类(Adapter2):

package adapte;
//适配器类---适配器(升级版电源)
//组合方式实现-->>对象适配器

public class Adapter2 implements AC2DC{

	private Adaptee a;
	
	public Adapter2(Adaptee a) {
		this.a=a;
	}
	
	public void handleRequest() {
		a.charge();
	}
	
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17

(5)客户端(Computer):

package adapte;
//客户端---电脑

//import java.io.InputStreamReader;

public class Computer {
	
	public void insert(AC2DC a) {
		//适配器(电脑充电需要的充电器)
		a.handleRequest();
	}
	
	public static void main(String[] args) {
		//电脑
		Computer computer=new Computer();
		//插座
		Adaptee adaptee=new Adaptee();
		//电源
		Adapter adapter=new Adapter();
		//升级电源
		Adapter2 a2=new Adapter2(adaptee);
		//充电
		computer.insert(a2);
		
		//字节流 -->> 字符流(应用了适配器模式)
//		InputStreamReader in = new InputStreamReader(in);
		
	}
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29

五、实现结果

图5-1 实现结果

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/木道寻08/article/detail/1021002
推荐阅读
相关标签
  

闽ICP备14008679号