• 设计模式-结构型模式-桥接模式


    桥接模式(Bridge Pattern):将抽象部分与其实现部分分离,使它们都可以独立地变化。它是一种对象结构型模式,又称为柄体(Handle and Body)模式或接口(Interface)模式。桥接模式用一种巧妙的方式处理多层继承存在的问题。桥接模式采用抽象关联取代了传统的多层继承,将类之间的静态继承关系转换为动态的对象组合关系,使得系统更加灵活,并易于扩展,同时有效控制了系统中类的个数。

    合成/聚合复用原则(CARP),尽量使用合成/聚合,尽量不要使用类继承。[J&DP]

     

     

    1. //首先,我们定义一个接口Implementor,它表示实现部分的接口
    2. public interface Implementor {
    3. void operationImpl();
    4. }
    5. //然后,我们创建两种实现这个接口的具体类:
    6. public class ConcreteImplementorA implements Implementor {
    7. @Override
    8. public void operationImpl() {
    9. System.out.println("ConcreteImplementorA operationImpl()");
    10. }
    11. }
    12. public class ConcreteImplementorB implements Implementor {
    13. @Override
    14. public void operationImpl() {
    15. System.out.println("ConcreteImplementorB operationImpl()");
    16. }
    17. }
    18. //接下来,我们定义一个抽象类Abstraction,它包含一个对Implementor的引用:
    19. public abstract class Abstraction {
    20. protected Implementor implementor;
    21. public Abstraction(Implementor implementor) {
    22. this.implementor = implementor;
    23. }
    24. public void operation() {
    25. implementor.operationImpl();
    26. }
    27. }
    28. //现在,我们创建两个继承自Abstraction的具体类,每个都接受一个特定的Implementor类型:
    29. public class RefinedAbstractionA extends Abstraction {
    30. public RefinedAbstractionA(Implementor implementor) {
    31. super(implementor);
    32. }
    33. }
    34. public class RefinedAbstractionB extends Abstraction {
    35. public RefinedAbstractionB(Implementor implementor) {
    36. super(implementor);
    37. }
    38. }
    39. //最后,在客户端代码中,我们可以根据需要组合抽象部分和实现部分:
    40. public class Client {
    41. public static void main(String[] args) {
    42. Implementor implementorA = new ConcreteImplementorA();
    43. Implementor implementorB = new ConcreteImplementorB();
    44. Abstraction abstractionA1 = new RefinedAbstractionA(implementorA);
    45. Abstraction abstractionA2 = new RefinedAbstractionA(implementorB);
    46. Abstraction abstractionB1 = new RefinedAbstractionB(implementorA);
    47. Abstraction abstractionB2 = new RefinedAbstractionB(implementorB);
    48. // 使用不同的组合调用operation
    49. abstractionA1.operation();
    50. abstractionA2.operation();
    51. abstractionB1.operation();
    52. abstractionB2.operation();
    53. }
    54. }

  • 相关阅读:
    (附源码)springboot校园闲置物品交易系统 毕业设计 521472
    jmeter负载测试中如何找到最大并发用户数(实战)
    数据结构——快排与归并
    【算法优选】 前缀和专题——贰
    Redis 源码简洁剖析 11 - 主 IO 线程及 Redis 6.0 多 IO 线程
    Halo 开源项目学习(六):事件监听机制
    达梦数据库表空间管理常用SQL
    元宇宙中的三大“派系”
    C++ STL 教程
    什么是EVM?以太坊EVM合约交互
  • 原文地址:https://blog.csdn.net/qq_34690079/article/details/136288661