装饰模式(Decorator),动态地给一个对象添加额外的职责,就增加功能来说,装饰模式比生成子类更为灵活。
装饰模式是为已有功能动态添加更多功能的一种方式,当系统需要更新的时候,是向旧的类中添加新的代码,这些新加的代码通常装饰了原有类的核心职责或主要行为。如果在已有的类中添加新的字段、新的方法和新的逻辑,从而增加了主类的复杂度,而这些新加入的东西仅仅是为了满足一些只在某种特定情况下才会执行的特殊行为需要。装饰模式把每个要装饰的功能放在单独的类中,并让这个类包装它所要装饰的对象,因此,当需要执行特殊行为时,客户代码就可以在运行时根据需要有选择、按顺序使用装饰。装饰模式的优点就是把类中的装饰功能从类中搬移出去,这样可以简化原有的类。
下面是装饰模式的UML图:
根据大话设计模式上的例子,利用C++对原有代码进行重写。代码如下所示:
//Person.h Person抽象父类
#ifndef __PERSON_H
#define __PERSON_H
#include <stdio.h>
#include <string.h>
const int MAX_NAME_LEN = ;
class Person
{
public:
virtual ~Person() {}
virtual void Show() = ;
protected:
char m_szName[MAX_NAME_LEN];
};
#endif // !__PERSON_H
//Professor.h 继承Person类
#ifndef __PROFESSOR_H
#define __PROFESSOR_H
#include "Person.h"
class Professor : public Person
{
public:
Professor( char* szName)
{
memset(m_szName, , MAX_NAME_LEN);
if (NULL == szName)
{
printf("szName = NULL\n");
memcpy(m_szName, "Professor", MAX_NAME_LEN);
}
else
{
memcpy(m_szName, szName, MAX_NAME_LEN);
}
}
~Professor() {}
virtual void Show()
{
printf("Show Professor:%s\n", m_szName);
}
};
#endif // !__PROFESSOR_H
//Decorator.h 装饰类 继承Person类
#ifndef __DECORATOR
#define __DECORATOR
#include "Person.h"
class Decorator : public Person
{
public:
Decorator()
{
m_pPerson = NULL;
}
~Decorator(){ }
void Decorate(Person *person)
{
if (person != NULL)
{
m_pPerson = person;
}
}
void Show()
{
if (m_pPerson)
{
m_pPerson->Show();
}
}
private:
Person *m_pPerson;
};
#endif
//Sneakers .h 继承Decorator类
#ifndef __SNEAKERS_H
#define __SNEAKERS_H
#include "Decorator.h"
class Sneakers : public Decorator
{
public:
Sneakers() {}
~Sneakers() {}
void Show()
{
printf("球鞋\n");
Decorator::Show();
}
};
#endif
对于重复的类这里就不再一一列举了。
最后运行结果如下: