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\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;
}

运行: 



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值