设计模式:decorator模式

本文通过一个具体的C++代码示例,介绍了装饰者模式的基本概念及其应用。装饰者模式允许在不修改原始类的情况下为其添加新的功能,通过桥接的方式保持装饰者与被装饰者之间的低耦合性。

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

两点:

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

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

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

例子:

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值