Bridge mode Bridge (c++ design mode)

Interviewer: Please talk about the bridge model


The abstract part and its realization decoupled portion , so that both can be varied independently.

Model advantages

  • Separate abstract interface and its implementation part
  • Can replace the multi-layer inheritance scheme, greatly reducing the number of subclasses
  • Improve the scalability of the system, expand one of the two changing dimensions arbitrarily, without modifying the original system, conforming to the principle of opening and closing

Model disadvantages

  • Will increase the difficulty of understanding and designing the system
  • It is not easy to correctly identify the two independently changing dimensions in the system

Applicable environment

  • Need to add more flexibility between abstraction and reification to avoid establishing a static inheritance relationship between the two levels
  • The abstract part and the implementation part can be extended independently by inheritance without affecting each other
  • A class has two or more independently changing dimensions, and these two or more dimensions need to be expanded independently
  • Do not want to use inheritance or a system where the number of system classes increases sharply due to multi-layer inheritance

Bridge mode code


/*
 * @ Description: C++ Design Patterns___Bridge
 * @ version: v1.0
 * @ Author: WeissxJ
 */
#include<iostream>

class Implementor
{
    
    
public:
    virtual ~Implementor() {
    
    }
  
    virtual void action() = 0;
  // ...
};

class ConcreteImplementorA : public Implementor
{
    
    
public:
  ~ConcreteImplementorA() {
    
    }
  
  void action()
  {
    
    
    std::cout << "Concrete Implementor A" << std::endl;
  }
  // ...
};

class ConcreteImplementorB : public Implementor
{
    
    
public:
  ~ConcreteImplementorB() {
    
    }
  
  void action()
  {
    
    
    std::cout << "Concrete Implementor B" << std::endl;
  }
  // ...
};

class Abstraction
{
    
    
public:
  virtual ~Abstraction() {
    
    }
  
  virtual void operation() = 0;
  // ...
};

class RefinedAbstraction : public Abstraction
{
    
    
public:
  ~RefinedAbstraction() {
    
    }
  
  RefinedAbstraction(Implementor *impl) : implementor(impl) {
    
    }
  
  void operation()
  {
    
    
    implementor->action();
  }
  // ...

private:
  Implementor *implementor;
};

int main()
{
    
    
  Implementor *ia = new ConcreteImplementorA;
  Implementor *ib = new ConcreteImplementorB;
  
  Abstraction *abstract1 = new RefinedAbstraction(ia);
  abstract1->operation();
  
  Abstraction *abstract2 = new RefinedAbstraction(ib);
  abstract2->operation();
  
  delete abstract1;
  delete abstract2;
  
  delete ia;
  delete ib;
  
  return 0;
}

Guess you like

Origin blog.csdn.net/qq_43477024/article/details/112891141