java架构师 设计模式之适配器模式

1、适配器模式

        在设计模式中,适配器模式(英语:adapter pattern)有时候也称包装样式或者包装(wrapper)。将一个类的接口转接成用户所期待的。一个适配使得因接口不兼容而不能在一起工作的类工作在一起,做法是将类自己的接口包裹在一个已存在的类中。

(1)适配器分类

适配器分为:类适配器、对象适配、接口适配方式

类适配器方式采用继承方式,对象适配方式使用构造函数传递

2、案例

        日本电饭煲电源接口标准是110V电压,而中国标准电压接口是220V,因此如果想在中国用日本电饭煲,需要一个电源转换器。

(1)110V电源接口

//日本110V 电源接口
public interface JP110VInterface {

	public void connect();

}

(2)110V电源接口实现

public class JP110VInterfaceImpl implements JP110VInterface {

	@Override
	public void connect() {
       System.out.println("日本110V,接通电源,开始工作..");
	}

}

(3)中国220V电源接口

public interface CN220VInterface {
	public void connect();
}

(4)中国220V电源实现

public class CN220VInterfaceImpl implements CN220VInterface {

	@Override
	public void connect() {
	 System.out.println("中国220V,接通电源,开始工作");
		
	}

}

(5)定义一个电饭煲

public class ElectricCooker {

	private JP110VInterface jp110VInterface;//日本电饭煲
	ElectricCooker(JP110VInterface jp110VInterface){
		 this.jp110VInterface=jp110VInterface;
	}
	
	public void cook(){
		jp110VInterface.connect();
		System.out.println("开始做饭了..");
	}

}

(6)电压适配器(要想在中国使用日本电饭煲,需要把电饭煲110v的电源接口适配成我们220V的电源接口,这就需要一个电源适配器

public class PowerAdaptor implements JP110VInterface {
	private CN220VInterface cn220VInterface;

	public PowerAdaptor(CN220VInterface cn220VInterface) {
		this.cn220VInterface = cn220VInterface;
	}

	@Override
	public void connect() {
		cn220VInterface.connect();
	}

}

(7)测试运行

public class AdaptorTest {

	public static void main(String[] args) {
		CN220VInterface cn220VInterface = new CN220VInterfaceImpl();
		PowerAdaptor powerAdaptor = new PowerAdaptor(cn220VInterface);
		// 电饭煲
		ElectricCooker cooker = new ElectricCooker(powerAdaptor);
		cooker.cook();//使用了适配器,在220V的环境可以工作了。
	}

}

3、使用场景

(1)使用第三方的类库,或者说第三方的API的时候,我们通过适配器转换来满足现有系统的使用需求。

(2)旧系统与新系统进行集成的时候,我们发现旧系统的数据无法满足新系统的需求,那么这个时候,我们可能需要适配器,完成调用需求。

(3)不同数据库之间进行数据同步。(我这里只是分析的是通过程序来说实现的时候的情况。

(4)OutputStreamWriter:是Writer的子类,将输出的字符流变为字节流,即:将一个字符流的输出对象变为字节流的输出对象。

(5)InputStreamReader:是Reader的子类,将输入的字节流变为字符流,即:将一个字节流的输入对象变为字符流的输入对象。

(6)SpringMVC 适配器

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值