设计模式系列学习十一:桥梁模式(Bridge)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
桥梁模式Bridge)是一种结构型设计模式,它将抽象部分与实现部分分离,使它们可以独立地变化。它通过将抽象类与实现类分开来解耦,从而可以在两者之间建立一个桥梁桥梁模式适用于以下情况: - 当你希望在运行时切换或扩展抽象部分和实现部分时。 - 当你想要避免在抽象部分中使用继承的情况。 在桥梁模式中,抽象部分(Abstraction)定义了抽象类,并且包含了对实现部分(Implementor)的引用。抽象类提供了一组方法或功能,可以通过委派给实现部分来执行。实现部分定义了一组方法,通过这些方法可以实现抽象类中定义的功能。 以下是一个简单的示例来说明桥梁模式的用法: ```java // 实现部分接口 interface Implementor { void operationImpl(); } // 具体实现类A class ConcreteImplementorA implements Implementor { public void operationImpl() { System.out.println("ConcreteImplementorA: operationImpl"); } } // 具体实现类B class ConcreteImplementorB implements Implementor { public void operationImpl() { System.out.println("ConcreteImplementorB: operationImpl"); } } // 抽象类 abstract class Abstraction { protected Implementor implementor; public Abstraction(Implementor implementor) { this.implementor = implementor; } public abstract void operation(); } // 扩展抽象类 class RefinedAbstraction extends Abstraction { public RefinedAbstraction(Implementor implementor) { super(implementor); } public void operation() { System.out.println("RefinedAbstraction: operation"); implementor.operationImpl(); } } public class BridgeExample { public static void main(String[] args) { Implementor implementorA = new ConcreteImplementorA(); Implementor implementorB = new ConcreteImplementorB(); Abstraction abstractionA = new RefinedAbstraction(implementorA); abstractionA.operation(); Abstraction abstractionB = new RefinedAbstraction(implementorB); abstractionB.operation(); } } ``` 输出结果: ``` RefinedAbstraction: operation ConcreteImplementorA: operationImpl RefinedAbstraction: operation ConcreteImplementorB: operationImpl ```

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值