Decorator Pattern


Goal: adding feature to a class, e.g. CPerson.
How: instead of subclassing, we use Person as a data member of the new class, e.g. Son.
By doing so, 1. no change to CPerson, 2. no calling the existing class’s constructor.
In this example below, we decorate CPerson so that it becomes a CSon, and 20 years later, we decorate the same person so that he becomes a CDad. CPerson’s constructor is only called once, at birth.
——————– code ——————–

class IPerson
{
public:
virtual void Talk() = 0;
};
class CPerson
{
public:
void Talk()
{
printf(” Person is constructed\n”);
};
};
class CSon: public IPerson
{
CPerson &mPerson;
public:
CSon(CPerson &person): mPerson(person)
{
};
void Talk()
{
printf(” I am a son\n”);
};
};
class CDad : public IPerson
{
CPerson &mPerson;
public:
CDad(CPerson &person) : mPerson(person)
{
};
void Talk()
{
printf(” I am a dady\n”);
};
};

int main()
{
const char* const msg = “person has been decorated into a”;
CPerson person;
person.Talk();
printf(“%s son\n”, msg);
CSon son(person);
son.Talk();
printf(“%s dady\n”, msg);
CDad dad(person);
dad.Talk();
return 0;
}
/*output
Person is constructed
person has been decorated into a son
I am a son
person has been decorated into a dady
I am a dady
*/

Advertisements
Previous Post
Next Post
Comments are closed.
%d bloggers like this: