Adaptor----设计模式

本文通过一个示例介绍了适配器(Adaptor)思想在编程中的应用,详细解释了如何使用适配器模式将不同接口的对象转换为统一的接口,以便于在程序中进行复用和扩展。

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

1.Adaptor适配器,比如我们的电脑有一个变压器,从220伏的交流电变成我们需要的XX伏。

即是我们不直接用220V的电源,我们用适配器给我们送出的电,而适配器用的是220V的电。

根据这样的思想写出如下的示例:

2.示例:

class Banner {
	private String str;
	public Banner(String str) {
		this.str = str;
	}	
	public void showWithParen() {
		System.out.println("(" + str + ")");
	}
	public void showWithAster() {
		System.out.println("*" + str + "*");
	}
	
}

interface Print {
	public abstract void printWeak();
	public abstract void printStrong();	
	
}

class PrintBanner extends Banner implements Print {
	public PrintBanner(String str) {
		super(str);
	}
	public void printWeak() {
		showWithParen();
	}
	public void printStrong() {
		showWithAster();
	}
	
}

public class Main {
	public static void main(String[] args) {
		PrintBanner pb = new PrintBanner("hello");
		pb.printWeak();
		pb.printStrong();
	}	
	
}

//这个例子貌似没什么艺术感,因为并没有任何的转换,变压器就像是把220V的电压转换成了220V的电压,不过还是用到了这样的思想,呵呵


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值