桥接模式

一、什么是桥接模式

        桥接模式,将抽象部分与实现部分分离,使它们都可以独立地变化。

二、UML 图


桥接模式UML实现

三、代码示例

1、 Implementor  实现

public interface Implementor {

        public void operation();

}

2、 Implementor 的实现A

public class ConcreteImplementorA implements Implementor{

        @Override

        public void operation() {

                System.out.println("实现A");

        }

}

3、 Implementor 的实现B

public class ConcreteImplementorB implements Implementor{

        @Override

        public void operation() {

                System.out.println("实现B");

        }

}

4、抽象

public abstract class Abstraction {

        protected Implementor implementor;

        public abstract void operation() ;

        public void setImplementor(Implementor implementor){

                    this.implementor = implementor;

         }

}

5、 Abstraction 的子类 Refrection

public class Refrection extends Abstraction{

        @Override

        public void operation() {

            implementor.operation();

        }

}

5、实现类

public class Main {

        public static void main(String[] args) {

                Abstraction ab = new Refrection();

                ab.setImplementor(new ConcreteImplementorA());

                ab.operation();

                ab.setImplementor(new ConcreteImplementorB());

                ab.operation();

        }

}


四、总结

        桥接模式将抽象和实现相分离的原因是实现有多种可能,那么就将实现分离出来,让其单独变化。实际应用场景比较多,如下图Spring Cache 和 Slf4j 的应用:

                实现系统可能有多角度分类,每一种分类都有可能变化,那么就把这种多角度分离出来让他们独立变化,减少它们之间的耦合。

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 为什么需要桥接模式?对象的关系是在编译时就定义好了,所以无法再运行时改变从父类继承的实现。子类的实现与它的父类有非...
    Mitchell阅读 2,435评论 0 0
  • 1 场景问题# 1.1 发送提示消息## 考虑这样一个实际的业务功能:发送提示消息。基本上所有带业务流程处理的系统...
    七寸知架构阅读 10,512评论 5 63
  • 1.初识桥接模式 将抽象部分与它的实现部分分离,使它们都可以独立地变化。 Abstraction:抽象部分的接口。...
    王侦阅读 4,463评论 0 7
  • 如果几年前有人对我说,嗨,二零一八年的你一事无成前途渺茫,我一定不相信。就像现在有人对我说,嗨,十年后的你穷困潦倒...
    海贼_王路飞阅读 1,592评论 0 1
  • 1、早上已经写了1500字,上午忙于工作而没有发出来,只能明天发了。这会继续搞定1500字,我的每天3000字的愿...
    阿白不急阅读 2,555评论 0 0