Skip to content

桥接模式

回到目录

简介

参考链接

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

问题的根本原因是我们试图在两个独立的维度——形状与颜色——上扩展形状类。桥接模式通过将继承改为组合的方式来解决这个问题。 具体来说, 就是抽取其中一个维度并使之成为独立的类层次, 这样就可以在初始类中引用这个新层次的对象, 从而使得一个类不必拥有所有的状态和行为。

成员对象就是就是桥接,成员对象实现了具体的实现,具象

UML类图

代码示例

#include <iostream>
#include <vector>
#include <string>
#include <memory>

class OperationSystem {
public:
  OperationSystem(const std::string &name): name_(name) {}

  std::string name_;
  virtual void printf_os() = 0;
};

// 具体的操作系统实现
class WindowsOS: public OperationSystem {
public:
  WindowsOS(const std::string &name): OperationSystem(name) {}
  virtual void printf_os() {std::cout << "OS is " << name_ << std::endl;}
};
class UbuntuOS: public OperationSystem {
public:
  UbuntuOS(const std::string &name): OperationSystem(name) {}
  virtual void printf_os() {std::cout << "OS is " << name_ << std::endl;}
};
class MacOS: public OperationSystem {
public:
  MacOS(const std::string &name): OperationSystem(name) {}
  virtual void printf_os() {std::cout << "OS is " << name_ << std::endl;}
};

// 电脑
class Computer {
public:
  Computer(const std::string &name, OperationSystem *os): name_(name), os_(os) {}

  OperationSystem *os_;
  std::string name_;
  virtual void printf_computer() = 0;
};

// 联想电脑
class LenovoComputer: public Computer {
public:
  LenovoComputer(const std::string &name, OperationSystem *os): Computer(name, os) {}
  virtual void printf_computer() {
    std::cout << "This computer is " << name_ << std::endl;
    std::cout << "This OS info " << std::endl;
    os_->printf_os();
  }
};

// 神州电脑
class HaseeComputer: public Computer {
public:
  HaseeComputer(const std::string &name, OperationSystem *os): Computer(name, os) {}
  virtual void printf_computer() {
    std::cout << "This computer is " << name_ << std::endl;
    std::cout << "This OS info " << std::endl;
    os_->printf_os();
  }
};

int main() {
  OperationSystem *windows = new WindowsOS("windows");
  OperationSystem *ubuntu = new WindowsOS("UbuntuOS");
  OperationSystem *mac = new WindowsOS("MacOS");

  Computer *lenovo = new LenovoComputer("lenovo", windows);
  Computer *hasee = new HaseeComputer("lenovo", ubuntu);

  lenovo->printf_computer();
  hasee->printf_computer();

  return 0;
}

/*
This computer is lenovo
This OS info 
OS is windows
This computer is lenovo
This OS info 
OS is UbuntuOS
*/