设计模式:bridge模式

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

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

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

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

例子:

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

猜你喜欢

转载自www.cnblogs.com/chusiyong/p/11433290.html