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

    目的:将抽象与实现相分离。
    定义:将抽象部分与它的实现部分分离,使他们都可以独立地变化。
    (抽象与实现分离是指让每种实现的变化不会影响到其他实现,从而打到应对变化的目的)
    代码如下:

    
    #include <list>
    #include <iostream>
    #include <string>
    using namespace std;
    /*实现*/
    class Implementor{
        public:
        virtual void Operation()=0;
    };
    /*具体实现*/ 
    class ImplementorA:public Implementor{
        public:
            void Operation()
            {
                cout<<"windows 版本"<<endl;
            }
    };
    class ImplementorB:public Implementor{
        public:
            void Operation()
            {
                cout<<"linux 版本"<<endl;
            }
    };
    /*抽象*/
    class  Abstraction{
        protected:
            /*之所以先构建实现类正是由于抽象必须实现对实现的通信*/
            Implementor * Base; 
        public:
            virtual void Operation()=0;
    }; 
    /*
       被提炼的抽象
       作用:当具体实现的时候接收具体实现的基类指针,建立起类间通信 
    */ 
    class RefinedAbstractionA:public Abstraction{
        public:
        RefinedAbstractionA(Implementor *t)
        {
            this->Base=t;
        }
        void SetOS(Implementor *t)
        {
            this->Base=t;
        }
        void Operation()
        {
            cout<<"dota:"; 
            Base->Operation();
        }
    };
    class RefinedAbstractionB:public Abstraction{
        public:
        RefinedAbstractionB(Implementor *t)
        {
            this->Base=t;
        }
        void SetOS(Implementor *t)
        {
            this->Base=t;
        }
        void Operation()
        {
            cout<<"LOL:";
             Base->Operation();
        }
    };
    int main(void)
    {
        Implementor *windows = new ImplementorA();
        Implementor *linux   = new ImplementorB();
        RefinedAbstractionA *dota = new RefinedAbstractionA(windows);
        dota->Operation();
        dota->SetOS(linux);
        dota->Operation();
        RefinedAbstractionB *lol = new RefinedAbstractionB(windows);
        lol->Operation();
        lol->SetOS(linux);
        lol->Operation();
        return 0;
    }
    

    实现系统可能有多角度分类,每一种分类都有可能变化,那么把这种多角度分离出来让他们独立变化,减少它们之间的耦合——大话设计模式
    何时使用桥接模式:
    在发现我们不得不多角度去分类实现对象,也就是不同操作系统之间的软件存在不同的实现,我们必须解决兼容问题,在这个时候大量的继承会造成大量的类增加,违背了开闭原则。
    问:在本次代码中如果我们需要开发新的软件怎么办?
    答:只用在Abstrction里添加派生类就可以了,然后在建立类间通信。

  • 相关阅读:
    页面滚动性能优化之passive
    【webpack4x】部分底层原理及手写一个简单打包工具
    【webpack4x】实战配置及问题解析
    【webpack4x】高级概念
    【webpack4x】核心概念
    VMware虚拟机服务的vmware-hostd自动启动和停止
    海淘电商网址
    一键批量ping任意ip段的存活主机
    cpanel导入大数据库(mysql)的方法
    awstats 日志分析
  • 原文地址:https://www.cnblogs.com/pzqu/p/9457646.html
Copyright © 2011-2022 走看看