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操作系统
    请按任意键继续. . .
  • 相关阅读:
    (C#基础) byte[] 之初始化, 赋值,转换。
    System.IO.IOException: The handle is invalid.
    .NET 自动内存管理(垃圾收集GC)
    Inconsistent accessibility
    有用的网址
    dw添加emmet
    行内标签,怎么取消两个标签中间的距离
    2016.6.2近日学习计划
    HTML5 input placeholder 颜色修改示例
    加入收藏和设为首页
  • 原文地址:https://www.cnblogs.com/onlycxue/p/3478521.html
Copyright © 2011-2022 走看看