Java 适配器模式

适配器模式使得接口不兼容的类可以一起工作

public class TestShipei {
	public static void main(String[] args) {
		PowerA powerAImple = new PowerAImple();
		PowerB powerBImple = new PowerBImple();
		Adapt ap = new Adapt(powerBImple);
		work(ap);
		
	}
	public static void work(PowerA pa) {
		System.out.println("正在连接");
		pa.insert();
		System.out.println("工作结束");
	}
}


//定义适配器,将两个接口的实现类组合在一起
class Adapt implements PowerA{
	
	PowerB pb;
	
	public Adapt(PowerB pb) {
		this.pb = pb;
	}
	
	@Override
	public void insert() {
		pb.connect();
	}	
}



interface PowerA{
	public void insert();
}

class PowerAImple implements PowerA{
	public void insert() {
		System.out.println("插入成功");
	}
}

interface PowerB{
	public void connect();
}

class PowerBImple implements PowerB{

	@Override
	public void connect() {
		System.out.println("连接成功");
	}
	
}

 

posted @ 2022-05-17 14:26  藤原豆腐渣渣  阅读(22)  评论(0编辑  收藏  举报