设计模式:decorator模式

两点:

  • 继承同一虚接口,实现数据一致性
  • 桥接方式指向被装饰类

目的:在不改变被装饰类功能的前提下增加新功能

特点:继承是子类和父类强耦合,桥接是低耦合

例子:

class Print //抽象接口
{
public:
	virtual int getColumns() = 0;  //横向
	virtual int getRows() = 0;     //纵向
	virtual string getRowContent(int row) = 0;
	virtual void show()
	{
		for(int i=0; i<getRows(); i++)
		{
			cout << getRowContent(i) << endl;
		}
	}
};

class TextPrint: public Print //具体装饰类
{
	string content;
public:
	TextPrint(string content)
	{
		this->content = content;
	}

	virtual int getColumns()
	{
		return content.size();
	};
	
	virtual int getRows()
	{
		return 1;
	}
	
	virtual string getRowContent(int row)
	{
		if(row == 0)
		{
			return content;
		}
		else
		{
			return NULL;
		}
	}
};

class Border: public Print //1.和被装饰物继承自同一接口,实现容器和内容的一致性
{
	char ch;
	Print* print;    //2.指向被装饰物
public:
	Border(char ch, Print* print)
	{
		this->ch = ch;
		this->print = print;
	}
	
	virtual int getColumns()
	{
		return 1 + print->getColumns() + 1;
	};
	
	virtual int getRows()
	{
		return 1 + print->getRows() + 1;
	}
	
	virtual string getRowContent(int row)
	{
		
		if(row == 0 || row == print->getRows() + 1)
		{
			string str = "";
			for(int i=0; i<getColumns(); i++)
			{
				str += ch;
			}
			
			return str;
		}
		else
		{
			return ch + print->getRowContent(row -1) + ch;
		}
	}
};
int main() 
{
	Border* border = new Border('*', new TextPrint("hello world"));
	border->show();
	
	cout << endl;
	
	Border* doubleBorder = new Border('+', border);
	doubleBorder->show();
	
	cout << endl;
	
	Border* trebleBorder = new Border('-', doubleBorder);
	trebleBorder->show();
	
	return 0;
}

//               打印结果如下:
//               *************
//               *hello world*
//               *************

//               +++++++++++++++
//               +*************+
//               +*hello world*+
//               +*************+
//               +++++++++++++++

//               -----------------
//               -+++++++++++++++-
//               -+*************+-
//               -+*hello world*+-
//               -+*************+-
//               -+++++++++++++++-
//               -----------------

  

原文地址:https://www.cnblogs.com/chusiyong/p/11433465.html