1.装饰者模式 Decorator
动态地给一个对象添加一个额外的职责, 就添加功能来说, 装饰模式比生成子类更为灵活。
每个装饰对象的实现和如何使用这个对象分离, 每个装饰对象只关心自己的功能,不需要关心如何被添加到对象链中。
实例:
人和衣服的装饰关系。
person.h Person类
#ifndef PERSON_H
#define PERSON_H #include <string>
#include <iostream>
using namespace std; class Person
{
public:
Person();
Person(string name);
void virtual show(); private:
string name; }; #endif // PERSON_H
person.cpp
#include "person.h" Person::Person()
{
} Person::Person(string name)
{
this->name = name;
} void Person::show()
{
cout << " <-name-> " << name << endl;
}
finery.h
#ifndef FINERY_H
#define FINERY_H #include "person.h" class Finery : public Person
{
public:
Finery();
void Decorate(Person *person);
void show(); protected:
Person *person; }; #endif // FINERY_H
finery.cpp
#include "finery.h" Finery::Finery()
{
} void Finery::Decorate(Person* person)
{
this->person = person;
} void Finery::show()
{
if(person != NULL)
person->show();
}
tshirts.h 装饰者
#ifndef TSHIRTS_H
#define TSHIRTS_H #include "finery.h" class TShirts : public Finery
{
public:
TShirts();
void show();
}; #endif // TSHIRTS_H
tshirts.cpp
#include "tshirts.h" TShirts::TShirts()
{
} void TShirts::show()
{
cout << " TShirts " << endl;
Finery::show();
}
bigtrouser.h
#ifndef BIGTROUSER_H
#define BIGTROUSER_H #include "finery.h" class BigTrouser : public Finery
{
public:
BigTrouser();
void show();
}; #endif // BIGTROUSER_H
bigtrouser.cpp
#include "bigtrouser.h" BigTrouser::BigTrouser()
{
} void BigTrouser::show()
{
cout << " BigTrouser " << endl;
Finery::show();
}
main.cpp
#include <iostream>
#include "tshirts.h"
#include "bigtrouser.h"
#include "person.h" using namespace std; int main()
{
cout << "Hello World!" << endl; Person *person = new Person("kevin"); TShirts *tshirt = new TShirts();
BigTrouser *bigT = new BigTrouser(); tshirt->Decorate(person);
bigT->Decorate(tshirt);
bigT->show(); return 0;
}