②JAVA设计模式笔记之适配器模式

本文通过生动的例子,详细解析了JAVA设计模式中的适配器模式,包括类适配器和对象适配器两种类型,展示了如何使现有类适应新的接口需求。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

JAVA设计模式笔记之适配器模式

适配器模式

用生活中的例子讲,适配器很像各种转换头,电源转换头啦、手机转换头啦

适配器模式分为两类

  • 类适配器
  • 对象适配器

举个栗子
现需要一辆可以在陆地上跑,也可以在水里开的两栖战车(目标接口)。
现有一辆仅可以在陆地上跑的战车(被适配者)。
现需造一个适配器,使得目标接口实现(适配器,一个具体的类)。

以下列子是类适配器

public interface Target {
	//目标接口
	public void canRun();
	
	public void canSwim();

}
public class CarOnlyRun {
	//现有的被适配者
	public void canRun(){
		System.out.println("我能在陆地上跑......");
	}

}
public class Adapter extends CarOnlyRun implements Target{
//类适配器
	@Override
	public void canSwim() {
		System.out.println("我能在水里上游......");
		
	}

}
public class Main {
	//实现
	public static void main(String[] args) {
		Target adapter = new Adapter();
		adapter.canRun();
		adapter.canSwim();
	}

}

以下例子是对象适配器

public interface Target {
	//目标接口
	public void canRun();
	
	public void canSwim();

}
public class CarOnlyRun {
	//现有的被适配者
	public void canRun(){
		System.out.println("我能在陆地上跑......");
	}

}
public class Adapter implements Target{
	//适配器仅实现接口,将被适配者设置为一个属性,使用构造函数传递进来
	private CarOnlyRun carOnlyRun;
	
	public Adapter(CarOnlyRun carOnlyRun) {
		super();
		this.carOnlyRun = carOnlyRun;
	}

	@Override
	public void canSwim() {
		System.out.println("我能在水里上游......");
		
	}

	@Override
	public void canRun() {
		this.carOnlyRun.canRun();
	}

}
public class Main {
	//实现
	public static void main(String[] args) {
		Target adapter = new Adapter(new CarOnlyRun());
		adapter.canRun();
		adapter.canSwim();
	}

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值