【设计模式】23-桥梁模式

本文深入探讨了桥梁模式的设计理念,解释了其如何通过解耦抽象与实现来提高代码的灵活性和可扩展性。桥梁模式适用于实现多变的场景,能够有效分离内部实现与外部逻辑,使高层抽象不受底层变化的影响。

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

什么是桥梁模式

桥梁模式一头连接抽象,一头连接实现。将原本在一起的逻辑通过抽象与实现解耦,使高层抽象的结构不随实际实现变化而变化。

 

为什么要用桥梁模式

应对实现多变的场景,桥梁模式能把外部逻辑抽象出去,从而将内部实现与外部抽象逻辑分离。

 

桥梁模式组成

外部抽象角色

public abstract class AbstractShell {

	private Implementor implementor;

	/**
	 * 子类需重新构造方法
	 * @param implementor implementor
	 */
	public AbstractShell(Implementor implementor) {
		this.implementor = implementor;
	}

	public void innerFun() {
		this.implementor.foo1();
	}

	public Implementor getImplementor() {
		return implementor;
	}
}

 

实现角色

public interface Implementor {
	void foo1();

	void foo2();
}

 

具体抽象角色

public class ComShell extends AbstractShell {

	public ComShell(Implementor implementor) {
		super(implementor);
	}

	@Override
	public void innerFun() {
		super.innerFun();
		super.getImplementor().foo2();
	}
}

 

具体实现角色

public class ComImplementor implements Implementor {
	@Override
	public void foo1() {
		System.out.println("com foo1");
	}

	@Override
	public void foo2() {
		System.out.println("com foo2");
	}
}

 

测试驱动

public class Client {

	public static void main(String[] args) {
		Implementor implementor = new ComImplementor();
		AbstractShell shell = new ComShell(implementor);
		shell.innerFun();
	}
}

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值