设为首页 加入收藏

TOP

Design Pattern Bridge 桥设计模式
2015-07-20 18:03:05 来源: 作者: 【 】 浏览:2
Tags:Design Pattern Bridge 设计模式

桥设计模式其实就是一个简单的has a relationship,就是一个类拥有另一个类,并使用另一个类实现需要的功能。

比如遥控器和电视之间可以使用桥设计模式达到可以使用同一个遥控器控制多台电视机的目的。

这样的设计思想是多种设计模式反反复复使用基本思想。

仔细思考下会发现多种设计模式的底层思想其实是相通的,不过具体实现或者某些细节,应用等有那么一点差别罢了。

下面就实现一个TV和remoter类,其中的remoter是可以随时更换的。

#include 
  
   

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

运行:



】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇HDU 3635 Dragon Balls 七龙珠 Un.. 下一篇UVA11549 Calculator Conundrum

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: