可以简记为pointer to implement:”指向实现的指针”。

 [DP]书上定义:将抽象部分与它的实现部分分离,使它们都可以独立地变化。考虑装操作系统,有多种配置的计算机,同样也有多款操作系统。如何运用桥接模式呢?可以将操作系统和计算机分别抽象出来,让它们各自发展,减少它们的耦合度。当然了,两者之间有标准的接口。这样设计,不论是对于计算机,还是操作系统都是非常有利的。下面给出这种设计的UML图,其实就是桥接模式的UML图。

c++桥接模式

c++桥接模式 

#include <bits/stdc++.h>
using namespace std;

#define debug(x) cout << #x << " at line " << __LINE__ << " is: " << x << endl

class COS
{
public:
    COS() {cout << "OS()" << endl;}
    virtual ~COS() {cout << "~OS()" << endl;}
    virtual void Run(){}
};

class CLinuxOS : public COS
{
public:
    CLinuxOS() {cout << "CLinuxOS()" << endl;}
    ~CLinuxOS() {cout << "~CLinuxOS()" << endl;}
    void Run(){cout << "LinuxOS run()" << endl;}
};

class CUnixOS : public COS
{
public:
    CUnixOS() {cout << "CUnixOS()" << endl;}
    ~CUnixOS() {cout << "~CUnixOS()" << endl;}
    void Run(){cout << "CUnixOS run()" << endl;}
};

class CComputer
{
public:
    CComputer() {cout << "CComputer()" << endl;}
    virtual ~CComputer() {cout << "~CComputer()" << endl;}
    virtual void InstallOS(COS *os){}
};

class CIBMComputer : public CComputer
{
public:
    CIBMComputer() {cout << "CIBMComputer()" << endl;}
    ~CIBMComputer() {cout << "~CIBMComputer()" << endl;}
    void InstallOS(COS *os){ os->Run();}
};

class CHPComputer : public CComputer
{
public:
    CHPComputer() {cout << "CHPComputer()" << endl;}
    ~CHPComputer() {cout << "~CHPComputer()" << endl;}
    void InstallOS(COS *os){ os->Run();}
};

int main(int argc, char *argv[])
{
    COS *os = new CLinuxOS();
    CComputer *cmptr = new CIBMComputer();
    cmptr->InstallOS(os);
    delete cmptr;
    cmptr = NULL;
    delete os;
    os = NULL;
    return 0;
}

 

 

第二个示例:

#ifndef SOLUTION_H
#define SOLUTION_H

struct CImplement;
class CAbstractSample
{
public:
    CAbstractSample();
    virtual ~CAbstractSample();
    void abstractDo();
private:
    CImplement *m_impl;
};

#endif // SOLUTION_H
solution.h

相关文章:

  • 2021-08-01
  • 2021-10-30
  • 2021-05-05
  • 2021-11-17
  • 2021-10-01
  • 2021-12-19
猜你喜欢
  • 2021-10-04
  • 2021-05-29
  • 2022-12-23
  • 2021-06-07
  • 2021-06-25
  • 2022-01-23
  • 2022-12-23
相关资源
相似解决方案