类图:
代码:
// Decorate.cpp : Defines the entry point for the console application.
//
//装扮模式:在已有的类上添加新的功能,对类的功能做扩展,把类的装饰功能分离出去,可以简化原有的类
#include "stdafx.h"
#include <string>
#include <iostream>
using namespace std;
//人
class Person
{
private:
string m_strName;
public:
Person(string strName)
{
m_strName=strName;
}
Person(){}
virtual void Show()
{
cout<<"装扮的是:"<<m_strName<<endl;
}
};
//装饰类
class Finery :public Person
{
protected:
Person* m_component;
public:
void Decorate(Person* component)
{
m_component=component;
}
virtual void Show()
{
m_component->Show();
}
};
//眼镜
class Gglasses:public Finery
{
public:
virtual void Show()
{
cout<<"Sunglasses"<<endl;
m_component->Show();
}
};
//披风
class TShirts: public Finery
{
public:
virtual void Show()
{
cout<<"Bule Shirts"<<endl;
m_component->Show();
}
};
//内裤
class Briefs :public Finery
{
public:
virtual void Show()
{
cout<<"Yellow Briefs"<<endl;
m_component->Show();
}
};
//客户端
int main()
{
Person *p=new Person("Superman");
Gglasses *gl=new Gglasses();
Briefs *bt=new Briefs();
TShirts *ts=new TShirts();
gl->Decorate(p);
bt->Decorate(gl);
ts->Decorate(bt);
ts->Show();
return 0;
}
Component是定义一个对象接口,可以给这些对象动态地添加职责,ConcreteComponent是定义了一个具体的对象,也可以给这个对象添加职责
Decorator装饰抽象类,继承Component从外类来扩展Component类的功能,但对于Compnent来说,是无需知道Decorator的存在的。至于
ConcereteDecorator就是具体的装饰对象,起到了给Component添加职责的功能
它的优点?
为已有功动态的添加更多功能的一种方式,有效的将类的核心功能和装饰功能分离