设计模式:bridge模式

本文通过具体的C++代码示例介绍了桥接模式的基本概念及其应用,详细展示了如何通过类的功能层次结构和实现层次结构来扩展类的功能,并讨论了这两种层次结构之间的区别。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

目的:将“类的功能层次结构”和“类的实现层次结构”分类

类的功能层次:通过类的继承添加功能(添加普通函数)

类的实现层次:通过类的继承实现虚函数

理解:和适配器模式中的桥接方法相同

例子:

class DisplayImpl
{
public:
	virtual void open() = 0;
	virtual void print() = 0;
	virtual void close() = 0;
};

 class StringDisplayImpl: public DisplayImpl //实现性扩展
 {
 public:
	void open()
	{
		cout << "open()" << endl;
	}
	
	void print()
	{
		cout << "print()" << endl;
	}
	
	void close()
	{
		cout << "close()" << endl;
	}
 };
class Display
{
	DisplayImpl* pImpl;   //桥接的核心代码
public:
	Display(DisplayImpl* pImpl)
	{
		this->pImpl = pImpl;
	}
	
	void print()
	{
		pImpl->open();
		pImpl->print();
		pImpl->close();
	}
};

class MultiDisplay: public Display //功能性扩展
{
public:
	MultiDisplay(DisplayImpl* pImpl): Display(pImpl)
	{}
	
	void multiPrint()
	{
		for(int i=0; i<5; i++)
		{
			print();
		}
	}
};
int main() 
{
	Display* d = new Display(new StringDisplayImpl());
	d->print();
	
	cout << endl;
	
	MultiDisplay* md = new MultiDisplay(new StringDisplayImpl());
	md->multiPrint();
	
	return 0;
}

 

转载于:https://www.cnblogs.com/chusiyong/p/11433290.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值