桥设计模式其实就是一个简单的has a relationship,就是一个类拥有另一个类,并使用另一个类实现需要的功能。
比如遥控器和电视之间可以使用桥设计模式达到可以使用同一个遥控器控制多台电视机的目的。
这样的设计思想是多种设计模式反反复复使用基本思想。
仔细思考下会发现多种设计模式的底层思想其实是相通的,不过具体实现或者某些细节,应用等有那么一点差别罢了。
下面就实现一个TV和remoter类,其中的remoter是可以随时更换的。
#include <stdio.h>
class Remoter
{
public:
virtual void changeChannel() = 0;
};
class OldRemoter : public Remoter
{
short channel;
public:
OldRemoter(short c) : channel(c) {}
void changeChannel()
{
printf("Channel : %d\n", channel++);
}
};
class NewRemoter : public Remoter
{
int channel;
public:
NewRemoter(int c) : channel(c) {}
void changeChannel()
{
printf("Channel : %d\n", channel++);
}
};
class TV
{
protected:
Remoter *remoter;
int channel;
public:
TV(Remoter *r) : remoter(r), channel(0) {}
virtual void changeRemoter(Remoter *r)
{
remoter = r;
}
virtual void changeChannel()
{
remoter->changeChannel();
}
};
class BrandOneTV : public TV
{
public:
BrandOneTV(Remoter *r) : TV(r){}
};
int main()
{
Remoter *ore = new OldRemoter(0);
Remoter *nre = new NewRemoter(1);
TV *tv1 = new BrandOneTV(ore);
tv1->changeChannel();
ore->changeChannel();
tv1->changeChannel();
tv1->changeRemoter(nre);
tv1->changeChannel();
nre->changeChannel();
tv1->changeChannel();
return 0;
}
运行: