Design Pattern Bridge 桥设计模式

桥设计模式事实上就是一个简单的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
", channel++);
	}
};

class NewRemoter : public Remoter
{
	int channel;
public:
	NewRemoter(int c) : channel(c) {}
	void changeChannel()
	{
		printf("Channel : %d
", 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;
}

执行: 



原文地址:https://www.cnblogs.com/mthoutai/p/6740885.html