设计模式_结构型模式_装饰器模式

装饰器模式和代理模式很像。
代理模式是已经知道代理谁了,所以只是对委托类的访问权限进行限制,因此用户只需要访问相应的代理类就可以。装饰器模式并不知道要装饰谁,所以需要传入具体的被装饰对象进行功能的添加

目的:

增加现有类的功能,但是,增加现有类的功能还有一个方法,就是新增加一个子类
添加子类的缺点:功能虽然可以完成,但是代码中有太多的子类添加进来,相同功能的代码大多相同,代码冗余严重
在这里插入图片描述

代码实现

#include<iostream>
#include<mutex>
#include<memory>
#include<unordered_map>
#include<list>
using namespace std;
class Car
{
   
public:
	virtual void Show() = 0;
};

class Bmw:public Car
{
   
public:
	void Show()
	{
   
		cout << "这是一辆宝马汽车:有基本配置" << " ";
	}
};
class Audi :public Car
{
   
public:
	void Show()
	{
   
		cout << "这是一辆奥迪汽车:有基本配置" << " ";
	}
};
class Benz :public Car
{
   
public:
	void Show()
	{
   
		cout << "这是一辆奔驰汽车:有基本配置" << " ";
	}
};

//装饰器1:定速巡航
class ConcreateDecorator01 :public Car
{
   
public:
	ConcreateDecorator01(Car*p):pCar(p){
   }
	void Show()
	{
   
		pCar->Show();
		cout << "定速巡航" << " ";
	}
private:
	Car* pCar;
};

//装饰器2:自动刹车
class ConcreateDecorator02 :public Car
{
   
public:
	ConcreateDecorator02(Car* p) :pCar(p) {
   }
	void Show()
	{
   
		pCar->Show();
		cout << "自动刹车" << " ";
	}
private:
	Car* pCar;
};
//装饰器3:车道偏离
class ConcreateDecorator03 :public Car
{
   
public:
	ConcreateDecorator03(Car* p) :pCar(p) {
   }
	void Show()
	{
   
		pCar->Show();
		cout << "车道偏离" << " ";
	}
private:
	Car* pCar;
};
int main()
{
   
	Car* p1 = new ConcreateDecorator01(new Bmw());
	p1= new ConcreateDecorator02(p1);
	p1 = new ConcreateDecorator03(p1);
	p1->Show();
	cout << endl;

	Car* p2 = new Audi();
	p2 = new ConcreateDecorator02(p2);
	p2->Show();
	cout << endl;
	Car* p3 = new Benz();
	p3->Show();
	cout << endl;
	return 0;
}

相关推荐

  1. GO设计模式——11、装饰模式结构

    2024-01-06 22:48:01       55 阅读
  2. 设计模式装饰模式结构)⭐⭐

    2024-01-06 22:48:01       30 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-01-06 22:48:01       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-01-06 22:48:01       100 阅读
  3. 在Django里面运行非项目文件

    2024-01-06 22:48:01       82 阅读
  4. Python语言-面向对象

    2024-01-06 22:48:01       91 阅读

热门阅读

  1. Kafka

    Kafka

    2024-01-06 22:48:01      56 阅读
  2. pytest装饰器:@pytest.mark.incremental

    2024-01-06 22:48:01       59 阅读
  3. AI:113-基于卷积神经网络的图像风格迁移

    2024-01-06 22:48:01       67 阅读
  4. C++垃圾回收机制

    2024-01-06 22:48:01       39 阅读
  5. 基于SpringBoot的在线考试系统绿色

    2024-01-06 22:48:01       67 阅读
  6. C#-数组

    2024-01-06 22:48:01       61 阅读
  7. ffmpeg 改变帧率,分辨率,时长等命令

    2024-01-06 22:48:01       59 阅读