设计模式(四):装饰器模式

设计模式(四):装饰器模式

定义:

​ ·动态的给一个对象添加一些额外的职能,把所需功能按顺序串联起来并进行控制。

主要解决:

​ ·当为了扩展一个类经常使用继承方式实现,由于继承为类引入静态特征,并且随着扩展功能的增多,子类会很膨胀。

何时使用:

​ ·在不想增多很多子类的情况下扩展类

以代码为例:

​ 类关系图如下

在这里插入图片描述

一、定义Component抽象类

为可以动态添加功能的对象定义接口

#include <iostream>

class Component
{
public:
  virtual ~Component() {}
  
  virtual void operation() = 0;
  // ...
};

二、定义ConcreteComponent类

创建实现Component类的实体类

class ConcreteComponent : public Component
{
public:
  ~ConcreteComponent() {}
  
  void operation()
  {
    std::cout << "Concrete Component operation" << std::endl;
  }
  // ...
};

三、定义装饰类

创建实现了Component类的装饰类

class Decorator : public Component
{
public:
  ~Decorator() {}
  
  Decorator( Component *c ) : component( c ) {}
  
  virtual void operation()
  {
    component->operation();
  }
  // ...

private:
  Component *component;
};
四、定义装饰器A和装饰器B

创建了两个扩展了 Decorator 类的实体装饰类。

class ConcreteDecoratorA : public Decorator//装饰器A
{
public:
  ConcreteDecoratorA( Component *c ) : Decorator( c ) {}//参数为Component类
  
  void operation()
  {
    Decorator::operation();
    std::cout << "Decorator A" << std::endl;
  }
  // ...
};

class ConcreteDecoratorB : public Decorator//装饰器B
{
public:
  ConcreteDecoratorB( Component *c ) : Decorator( c ) {}//参数为Component类
  
  void operation()
  {
    Decorator::operation();
    std::cout << "Decorator B" << std::endl;
  }
  // ...
};

五、main函数设计

int main()
{
  ConcreteComponent  *cc = new ConcreteComponent();
  ConcreteDecoratorB *db = new ConcreteDecoratorB( cc );
  ConcreteDecoratorA *da = new ConcreteDecoratorA( db );
  
  Component *component = da;
  component->operation();
  
  delete da;
  delete db;
  delete cc;
  
  return 0;
}

运行结果

在这里插入图片描述
装饰器模式优缺点:

优点:

​ ·装饰类和被装饰类可以独立发展,不会相互耦合,装饰模式是继承的一个替代模式,装饰模式可以动态扩展一个实现类的功能。

缺点:

​ ·多层装饰比较复杂。

注意事项:

​ ·可以代替继承

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值