zoukankan      html  css  js  c++  java
  • 设计模式: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;
    }
    
  • 相关阅读:
    bzoj 1087 状压dp
    HDU 5289 尺取
    HDU 1693 插头dp入门详解
    字符串操作
    河南省多校联萌(一)
    HDU 4815 概率dp,背包
    HDU4804 Campus Design (轮廓线DP)
    HDU 4828 逆元+catalan数
    HDU 5651 组合+逆元
    天才少年曹原的内心
  • 原文地址:https://www.cnblogs.com/chusiyong/p/11433290.html
Copyright © 2011-2022 走看看