• 设计模式: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;
    }
    
  • 相关阅读:
    React class & function component 的区别
    Webpack 4 + React + Typescript 搭建启动模版
    JavaScript的数据类型及其检测
    react SyntheticEvent 合成事件机制
    数组的排序
    Ajax 和 Ajax的封装
    go 结构的方法总结
    go 结构的方法2
    go struct 的方法1
    go 函数闭包
  • 原文地址:https://www.cnblogs.com/chusiyong/p/11433290.html
Copyright © 2020-2023  润新知