设计模式之桥接模式BridgePattern(十二)

一、桥接模式介绍

桥接模式(bridge pattern) 的定义是:将抽象部分与它的实现部分分离,使它们都可以独立地变化。

桥接模式用一种巧妙的方式处理多层继承存在的问题,用抽象关联来取代传统的多层继承,将类之间的静态继承关系转变为动态的组合关系,使得系统更加灵活,并易于扩展,有效的控制了系统中类的个数 (避免了继承层次的指数级爆炸)。

二、桥接模式结构 

  • 抽象化(Abstraction)角色 :主要负责定义出该角色的行为 ,并包含一个对实现化对象的引用。
  • 扩展抽象化(RefinedAbstraction)角色 :是抽象化角色的子类,实现父类中的业务方法,并通过组合关系调用实现化角色中的业务方法。
  • 实现化(Implementor)角色 :定义实现化角色的接口,包含角色必须的行为和属性,并供扩展抽象化角色调用。
  • 具体实现化(Concrete Implementor)角色 :给出实现化角色接口的具体实现。

三、使用场景

  • 如果一个系统需要在构件的抽象化角色和具体化角色之间增加更多的灵活性,避免在两个层次之间建立静态的继承联系,通过桥接模式可以使它们在抽象层建立一个关联关系
  • 对于那些不希望使用继承或因为多层次继承导致系统类的个数急剧增加的系统,桥接模式尤为适用
  • 一个类存在两个独立变化的维度,且这两个维度都需要进行扩展

四、代码实例

1、Implementor

package com.xu.demo.bridgePattern;

/**
 * 实现类接口
 */

public interface Implementor {

    void operationImpl();
}

2、ConcreteImplementorA

package com.xu.demo.bridgePattern;

/**
 * 具体实现类A
 */

public class ConcreteImplementorA implements Implementor {

    @Override
    public void operationImpl() {
        System.out.println("Concrete ImplementorA operation.");
    }
}

 3、ConcreteImplementorB

package com.xu.demo.bridgePattern;

/**
 * 具体实现类B
 */

public class ConcreteImplementorB implements Implementor {

    @Override
    public void operationImpl() {
        System.out.println("Concrete ImplementorB operation.");
    }
}

 

4、Abstraction

package com.xu.demo.bridgePattern;

/**
 * 抽象类接口
 */
public abstract class Abstraction {

    protected Implementor implementor;

    public Implementor getImplementor() {
        return implementor;
    }

    public void setImplementor(Implementor implementor) {
        this.implementor = implementor;
    }

    public Abstraction(Implementor implementor) {
        this.implementor = implementor;
    }

    public abstract void operation();
}

5、RefinedAbstraction

package com.xu.demo.bridgePattern;

/**
 * 扩展类
 */
public class RefinedAbstraction extends Abstraction {

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

    @Override
    public void operation() {
        implementor.operationImpl();
    }
}

 6、BridgePattern

package com.xu.demo.bridgePattern;

/**
 * 桥接模式
 */
public class BridgePattern {

    public static void main(String[] args) {

        Abstraction abstraction = new RefinedAbstraction(new ConcreteImplementorA());
        abstraction.operation(); // 输出: Concrete ImplementorA operation.

        abstraction.setImplementor(new ConcreteImplementorB());
        abstraction.operation(); // 输出: Concrete ImplementorB operation.
    }

}

 运行结果:

至此,一个简单的桥接模式的实例就完成了,好好学习认真体会,你也能成为IT高手,我们下回再见。

  • 5
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

易雪寒

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

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

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

打赏作者

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

抵扣说明:

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

余额充值