【java设计模式】-08桥接模式

版权声明:本文为博主原创文章,转载请注明出处 https://blog.csdn.net/u010647035/article/details/85226647

1、概述

桥接(Bridge)是用于把抽象与实现解耦,使二者可以独立变化。这种类型的设计模式属于结构型模式,它通过提供抽象化和实现化之间的桥接结构,来实现二者的解耦。

2、模式结构

桥接模式包含如下角色:

Abstraction:抽象类

RefinedAbstraction:扩充抽象类

Implementor:实现类接口

ConcreteImplementor:具体实现类

在这里插入图片描述

3、代码实现

3.1、创建实现类接口

/**
 * 具体实现类接口
 *
 * @author kaifeng
 * @date 2018/12/23
 */
public interface Implementor {
    /**
     * 需要实现的操作
     */
    void operationImpl();
}

3.2、创建抽象类

/**
 * 抽象类
 *
 * @author kaifeng
 * @date 2018/12/23
 */
abstract class Abstraction {
    /**
     * 持有一个 Implementor 对象
     */
    private Implementor implementor;

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

    /**
     * 调用实现的具体方法
     */
    public void operation() {
        implementor.operationImpl();
    }
}

3.3、创建具体实现类

/**
 * 实现类A
 *
 * @author kaifeng
 * @date 2018/12/23
 */
public class ConcreteImplementorA implements Implementor {
    @Override
    public void operationImpl() {
        System.out.println("我是具体实现类A");
    }
}

/**
 * 实现类B
 *
 * @author kaifeng
 * @date 2018/12/23
 */
class ConcreteImplementorB implements Implementor {
    @Override
    public void operationImpl() {
        System.out.println("我是具体实现类B");
    }
}

3.4、创建扩充抽象类

/**
 * 扩充实现类
 *
 * @author kaifeng
 * @date 2018/12/23
 */
public class RefinedAbstraction extends Abstraction {

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

    public void otherOperation() {
        System.out.println("我是其它操作");
    }
}

3.5、客户端调用

/**
 * 客户端调用
 *
 * @author kaifeng
 * @date 2018/12/23
 */
public class BridgePatternDemo {
    public static void main(String[] args) {
        //实例化具体实现
        Implementor implementor = new ConcreteImplementorA();
        //初始化扩充实现类
        RefinedAbstraction abstraction = new RefinedAbstraction(implementor);
        //通过扩充实现类调用具体方法
        abstraction.operation();
        //调用扩充实现类的扩充方法
        abstraction.otherOperation();
    }
}

输出

我是具体实现类A
我是其它操作

4、适用场景

1、如果一个系统需要在构件的抽象化角色和具体化角色之间增加更多的灵活性,避免在两个层次之间建立静态的继承联系,通过桥接模式可以使它们在抽象层建立一个关联关系。

2、对于那些不希望使用继承或因为多层次继承导致系统类的个数急剧增加的系统,桥接模式尤为适用。

3、一个类存在两个独立变化的维度,且这两个维度都需要进行扩展。

5、优缺点

优点

1、分离抽象接口及其实现部分。提高了比继承更好的解决方案。

2、桥接模式提高了系统的可扩充性,在两个变化维度中任意扩展一个维度,都不需要修改原有系统。

3、实现细节对客户透明,可以对用户隐藏实现细节。

缺点

1、桥接模式的引入会增加系统的理解与设计难度,由于聚合关联关系建立在抽象层,要求开发者针对抽象进行设计与编程。

2、桥接模式要求正确识别出系统中两个独立变化的维度,因此其使用范围具有一定的局限性。

猜你喜欢

转载自blog.csdn.net/u010647035/article/details/85226647