Java设计模式--适配器模式

Java设计模式–适配器模式

  • 定义
    将一个类的接口转换成客户希望的另一个接口。Adapter模式使得原本由于接口不兼容而不能一起工作的那些类可以一起工作

  • 实现

  • 1对象适配器模式

public class AdapterTest1 {
	public static void main(String[] args) {
		Adaptee adaptee = new Adaptee();
		Target target=new Adapter(adaptee);
		target.output5v();
	}
}
class Adaptee{
	public int output220v() {
		return 220;
	}
}
interface Target{
	int output5v();
}
class Adapter implements Target{
	private Adaptee adaptee;
	public Adapter(Adaptee adaptee) {
		this.adaptee=adaptee;
	}
	@Override
	public int output5v() {
		// TODO Auto-generated method stub
		int i=adaptee.output220v();
		//一些列转变
		System.out.println(String.format("原始电压: %d v  ----> 输出电压: %d v", i,5));
		return 5;
	}
	
}

  • 2.类的适配器模式
public class AdapterTest2 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Adapter2 adapter2=new Adapter2();
		adapter2.output5v();
	}

}
class Adaptee2{
	public int output220v() {
		return 220;
	}
}
interface Target2{
	int output5v();
}
class Adapter2 extends Adaptee implements Target2{

	@Override
	public int output5v() {
		// TODO Auto-generated method stub
		int i=output220v();
		//一些列转变
		System.out.println(String.format("原始电压: %d v  ----> 输出电压: %d v", i,5));
		return 5;
	}
	
}

本质上,类的适配器模式用的是继承,而对象的适配器模式用的时组合,但是类的适配器本身会污染接口,不符合迪米特法则(最少知道原则)

  • 应用场景
  •  1.当你希望使用某些类,但其接口与你的其他代码不兼容时,请使用适配器类
     2.当你希望重用几个现有的子类,这些子类缺少一些不能添加到超类中的公共功能时,请使用该模式
    
  • 优点
  •  1.符合单一职责原则
     2.符合开闭原则
    
  • 源码的应用
  •  JDK:
     java.util.Arrays#asList()
     java.util.Collections#list()
     Spring:
     org.springframework.context.event.GenericApplictionListenerAdapter
    
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值