装饰模式(decorator),动态地给一个对象添加一些额外的职责,就增加功能来说,装饰模式比生成子类更为灵活。
说白了就是扩展一个类的功能,而又不想用继承。
不废话先看UML和一段代码吧:
对应代码:
#include <iostream>
using namespace std;
class People
{
public:
People(string name,string profession):Name(name),Profession(profession){}
virtual void Introduce_slef() = 0;
void IntroduceName()
{
cout << "My name is: " << Name << endl;
}
void IntroduceProfession()
{
cout << "My profession is: " << Profession << endl;
}
private:
string Name;
string Profession;
};
class Student:public People
{
public:
Student(string name,string profession,string school):People(name,profession)
,School(school){}
void Introduce_slef()
{
IntroduceName();
IntroduceProfession();
}
void Learn()
{
}
//other interface
private:
string School;
};
class Teacher:public People
{
public:
Teacher(string name,string profession,int year):People(name,profession),
WorkYear(year){}
void Introduce_slef()
{
IntroduceName();
IntroduceProfession();
}
void Teach()
{
}
//other interface
private:
int WorkYear;
};
class DecoratorPeople
{
public:
DecoratorPeople(int id):ID(id),pl(NULL){}
void Decorator(People *p)
{
pl = p;
}
void IntroduceId()
{
cout << "My ID is: " << ID << endl;
}
void Introduce_slef()
{
IntroduceId();
pl->Introduce_slef();
}
private:
int ID;
People *pl;
};
int main()
{
People *p = new Teacher("xiaozhang","teacher",5);
People *p1 = new Student("xiaowang","student","New York");
DecoratorPeople md(3001);
md.Decorator(p);
md.Introduce_slef();
md.Decorator(p1);
md.Introduce_slef();
delete p;
delete p1;
return 0;
}
据上述UML图和代码我们来介绍一下什么叫装饰模式,它是如何起到添加功能的作用的。
抽象了一个People类,派生了Student和Teacher两个具体类,
从抽象类又派生了一个DecoratorPeople类,这个类来给People添加功能,就是所谓的装饰类
这里其实就是对多态的灵活运用,研究了这么长时间本人认为所有设计模式都是对多态的灵活运用,离开多态一切免谈。要不然c语言为什么没有设计模式?
职责单一原则,依赖倒转原则,开放封闭原则这里几乎全部用到了。
设计模式也就是以原则为前提,灵活运用多态,然后考虑实际应用程序可能的维护和扩展,其实也并不深奥。