bridge pattern的c++代码样例与分析

来源:互联网 发布:江苏飚风软件 编辑:程序博客网 时间:2024/05/15 23:43

(@转载请注明出处:http://blog.csdn.net/cmatch

 

因为互联网上大部分讲解模式程序样例都是用java等语言描述的,为了方便c++爱好者便于学习,我将使用c++来讲解模式。

bridge模式,程序样例,如下:

 

#include <iostream>

using namespace std;

class Imp {
public:
        virtual void operation() = 0;
};

class ImpA: public Imp {
public:
        void operation() {
                cout << "A from Imp" << endl;
        }
};

class ImpB: public Imp {
public:
        void operation() {
                cout << "B from Imp" << endl;
        }
};

class A {
public:
        virtual void print() {}
        A(Imp * imp): imp(imp) {}
        A(): imp(NULL) {}
        void setTool(Imp *imp) {
                this->imp = imp;
        }
protected:
        Imp * imp;
};


class A1: public A {
public:
        A1():A() {}
        A1(Imp *imp):A(imp) {}
        void print() {
                cout << "come from A1" << endl;
                imp->operation();
        }
};

class A2: public A {
public:
        A2():A() {}
        A2(Imp *imp):A(imp) {}
        void print() {
                //something to do
                cout << "come from A2" << endl;
                imp->operation();
        }
};


int main () {
        Imp *b = new ImpA;

        A *a = new A1;
        a->setTool(b);
        a->print();

        delete b;

        b = new ImpB;
        a->setTool(b);
        a->print();

        delete b;
        delete a;


        A1 objA(new ImpA);
        objA.print();

        A1 objB(new ImpB);
        objB.print();

        return 0;
}

 

分析如下:

(待续)