zoukankan      html  css  js  c++  java
  • 设计模式--桥梁模式C++实现

    1定义

    将抽象和实现解耦,使得两者可以独立变化

    2类图

    3实现

    #pragma once
    #include<iostream>
    using namespace std;
    
    class Implementor
    {
    protected:
        Implementor(){}
    public:
        virtual ~Implementor() = 0{}
    
        virtual void doSomething() = 0;
        virtual void doAnything() = 0;
    };
    
    class ConcreteImplementor1 :public Implementor
    {
    public:
        void doSomething()
        {
            cout << "1doSomething();" << endl;
        }
        void doAnything()
        {
            cout << "1doAnything();" << endl;
        }
    };
    class ConcreteImplementor2 :public Implementor
    {
    public:
        void doSomething()
        {
            cout << "2doSomething();" << endl;
        }
        void doAnything()
        {
            cout << "2doAnything();" << endl;
        }
    };
    
    class Abstraction
    {
    private:
        Implementor *_imp;
    public:
        Abstraction(Implementor * imp)
            :_imp(imp)
        {}
    
        virtual void request()
        {
            _imp->doSomething();
        }
        Implementor* getImp()
        {
            return _imp;
        }
    };
    
    class RefinedAbstraction :public Abstraction
    {
    public:
        RefinedAbstraction(Implementor* imp)
            :Abstraction(imp)
        {}
    
        void request()
        {
            Abstraction::request();
            Abstraction::getImp()->doAnything();
        }
    };
    
    class Client
    {
    public:
        void operator()()
        {
            Implementor* imp = new ConcreteImplementor1();
            Abstraction* abs = new RefinedAbstraction(imp);
            abs->request();
        }
    };

    4应用

    ①优点

    抽象和实现分离

    完全为了解决集成的缺点而提出的设计模式////抽象与实现的关系本来是纵向的,桥梁模式将他们改为横向关系

    优秀的扩充能力

    实现细节对客户透明

    5使用场景

    不希望或者不适合通过继承的场景

    接口或者抽象类不稳定

    重要性要求较高的场景

    6注意事项

    使用桥梁模式重点在于如何拆分抽象和实现,并不是以设计继承就考虑使他,桥梁的意图是对变化进行封装

  • 相关阅读:
    win7常用快捷键
    java中构造代码块、方法调用顺序问题
    eclipse项目改为maven项目导致svn无法比较历史数据的解决办法
    linux配置Anaconda python集成环境
    DataFrame对行列的基本操作实战
    驱动:电阻屏触摸芯片NS2009
    读书笔记:代码大全(第二版)
    资料:磁角度传感器芯片
    经验:FatFs文件系统实时写入
    笔记:CAN收发器-TJA1051T与TJA1051T/3调试总结
  • 原文地址:https://www.cnblogs.com/lang5230/p/5371409.html
Copyright © 2011-2022 走看看