设计模式之桥接模式

        桥接模式是一种结构型设计模式,它将抽象部分与其实现部分分离,使它们可以独立地变化。桥接模式通过将继承关系转化为关联关系,实现了抽象部分和实现部分的解耦。

        在桥接模式中,抽象部分定义了一个抽象接口,包含了对实现部分的引用。实现部分定义了具体的实现类,并实现了抽象接口中定义的方法。抽象部分和实现部分通过关联关系连接在一起,而不是通过继承关系。

桥接模式的关键要素包括:

  • 抽象部分:定义了抽象接口,包含对实现部分的引用。
  • 具体抽象部分:继承自抽象部分,对抽象接口进行扩展和改造。
  • 实现部分:定义了实现接口,提供具体的实现类。
  • 具体实现部分:实现实现部分的接口,并提供具体的实现。

桥接模式的优点包括:

  • 分离抽象和实现,使得两者可以独立地变化和演化。
  • 提高了系统的灵活性和可扩展性,方便进行组合和修改。
  • 降低了系统的耦合性,减少了继承的使用。

下面是一个简单的桥接模式示例:

// 抽象部分
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() {
        implementor.operationImpl();
    }
}

// 实现部分
interface Implementor {
    void operationImpl();
}

// 具体实现部分
class ConcreteImplementorA implements Implementor {
    public void operationImpl() {
        System.out.println("ConcreteImplementorA operationImpl");
    }
}

class ConcreteImplementorB implements Implementor {
    public void operationImpl() {
        System.out.println("ConcreteImplementorB operationImpl");
    }
}

// 客户端代码
public class Client {
    public static void main(String[] args) {
        Implementor implementorA = new ConcreteImplementorA();
        Abstraction abstractionA = new RefinedAbstraction(implementorA);
        abstractionA.operation();

        Implementor implementorB = new ConcreteImplementorB();
        Abstraction abstractionB = new RefinedAbstraction(implementorB);
        abstractionB.operation();
    }
}

输出结果:

       在上述示例中,我们有一个抽象部分Abstraction,它包含了对实现部分Implementor的引用。具体抽象部分RefinedAbstraction继承自抽象部分,并通过实现抽象部分中定义的方法来调用实现部分的具体实现。

        实现部分包含了实现接口Implementor,并有具体的实现类ConcreteImplementorAConcreteImplementorB。这些实现类提供了不同的实现方式。

        在客户端代码中,我们创建了具体的实现部分对象,并将其传递给具体抽象部分对象。通过调用具体抽象部分的方法,实现部分的具体实现得以调用。

        通过桥接模式,我们可以将抽象部分和实现部分解耦,使得它们可以独立地变化和演化。这种方式提高了系统的灵活性和可扩展性,并降低了系统的耦合性。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

鲤鱼程序员

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值