• 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操作系统
    请按任意键继续. . .
  • 相关阅读:
    电子工程师对程序员的一番心里话(转载)
    一个程序员的一生(转载)
    程序人生中的十个感悟...
    谈计算机软件发展观念(转载)
    ASP.NET 2.0服务器控件开发精要(转载)
    一个老程序员的心里话(转载)
    hdu 1316 斐波那契数
    hdu 3117 斐波那契数列
    hdu 1239 素数水题
    hdu 2256 神奇的矩阵
  • 原文地址:https://www.cnblogs.com/onlycxue/p/3478521.html
Copyright © 2020-2023  润新知