zoukankan      html  css  js  c++  java
  • c++ 桥接模式(bridge)

    桥接模式的目的是分离抽象实现部分,把数据和实现分开,降低耦合。桥接模式和适配器模式不同之处是,桥接模式一般会在软件设计初考虑使用,适配器模式在软件设计之后为了实现接口兼容时使用。

    下面是系统和电脑之间的桥接模式的使用

    #include <iostream>
    using namespace std;
    
    class OS
    {
    public:
        virtual void NameOS()
        {
    
        }
    };
    
    class WindowOS:public OS
    {
    public:
        void NameOS()
        {
            cout << "安装Window操作系统" <<endl;
        }
    
    };
    
    class LinuxOS:public OS
    {
    public:
        void NameOS()
        {
            cout <<  " 安装Linux操作系统" <<endl;
        }
    };
    
    class UnixOS:public OS
    {
    public:
        void NameOS()
        {
            cout << "安装Unix操作系统" <<endl;
        }
    };
    
    class Computer
    {
    public:
        Computer(OS *osptr):m_osPtr(osptr)
        {
        
        }
        virtual void InstallOs() = 0;
    protected:
        OS *m_osPtr;
    };
    
    class DellComputer:public Computer
    {
    public:
        DellComputer(OS *osptr):Computer(osptr)
        {
        
        }
    
        void InstallOs()
        {
            cout << "Dell Computer" << endl;
            m_osPtr->NameOS();
        }
    };
    
    class ToshibaComputer:public Computer
    {
    public:
        ToshibaComputer(OS *osptr):Computer(osptr)
        {
        
        }
        void InstallOs()
        {
            cout << "ToShiBa Computer" << endl;
            m_osPtr->NameOS();
        }
    };
    
    int main()
    {
        DellComputer * DellPtr1 = new DellComputer(new WindowOS);
        DellPtr1->InstallOs();
    
        DellComputer * DellPtr2 = new DellComputer(new LinuxOS);
        DellPtr2->InstallOs();
    
        ToshibaComputer *ToshibaPtr1 = new ToshibaComputer(new WindowOS);
        ToshibaPtr1->InstallOs();
    
        ToshibaComputer *ToshibaPtr2 = new ToshibaComputer(new LinuxOS);
        ToshibaPtr2->InstallOs();
    
        system("pause");
    
        return 0;
    }

    输出结果:

    Dell Computer
    安装Window操作系统
    Dell Computer
     安装Linux操作系统
    ToShiBa Computer
    安装Window操作系统
    ToShiBa Computer
     安装Linux操作系统
    请按任意键继续. . .
  • 相关阅读:
    ERROR: epmd error for host "yourhostname": timeout
    leetcode485
    leetcode463
    leetcode496
    leetcode344
    leetcode412
    leetcode500
    leetcode476
    leetcode557
    leetcode461
  • 原文地址:https://www.cnblogs.com/onlycxue/p/3478521.html
Copyright © 2011-2022 走看看