C++桥接模式(Bridge)

 C++
时间:

使用场景

  1. 系统需要使用一些现有的类,而这些类的接口(如方法名)不符合系统的需要,甚至没有这些类的源代码。

  2. 想创建一个可以重复使用的类,用于与一些彼此之间没有太大关联的一些类,包括一些可能在将来引进的类一起工作。

  3. 有动机地修改一个正常运行的系统的接口,这时应该考虑使用适配器模式。

Bridge

#include<iostream>

using namespace std;

class AbstractionImp
{
    public:
        virtual ~AbstractionImp() { cout << "AbstractionImp....." << endl; }
        virtual void Operation() = 0;
    protected:
        AbstractionImp() {}
    private:
};

class ConcreteAbstractionImpA : public AbstractionImp
{
    public:
        ConcreteAbstractionImpA() { cout << "ConcreteAbstractionImpA....." << endl; }
        ~ConcreteAbstractionImpA() {}
        virtual void Operation() { cout << "Operation ConcreteAbstractionImpA......" << endl; }
    protected:
    private:
};

class ConcreteAbstractionImpB : public AbstractionImp
{
    public:
        ConcreteAbstractionImpB() { cout << "ConcreteAbstractionImpB....." << endl; }
        ~ConcreteAbstractionImpB() {}
        virtual void Operation() { cout << "Operation ConcreteAbstractionImpB......" << endl; }
    protected:
    private:
};

class Abstraction
{
    public:
        Abstraction(AbstractionImp* imp) : _imp(imp){}
        ~Abstraction() {}
        virtual void Operation() = 0;
    protected:
        Abstraction() {}
    private:
        AbstractionImp* _imp;
};

class RefinedAbstraction : public Abstraction
{
    public:
        RefinedAbstraction(AbstractionImp* imp) : _imp(imp){}
        ~RefinedAbstraction();
        void Operation() { this->_imp->Operation(); }
    protected:
        RefinedAbstraction() {}
    private:
        AbstractionImp* _imp;
};


int main(int argc, char* argv[])
{
    AbstractionImp* imp = new ConcreteAbstractionImpA();
    Abstraction* abs = new RefinedAbstraction(imp);

    AbstractionImp* imp2 = new ConcreteAbstractionImpB();
    Abstraction* abs2 = new RefinedAbstraction(imp2);

    abs->Operation();
    abs2->Operation();
    return 0;
}

0 评论