装饰模式:
装饰模式(Decorator),动态地给一个对象添加一些额外的职责,就是增加功能,装饰模式比生成子类更为灵活。
Component是定义一个对象接口,可以给这些对象动态地添加职责。ConcreteComponent是定义了一个具体的对象,也可以给这个对象添加一些职责。Decorator,装饰抽象类,继续了Component,从外类来扩展Component类的功能,但对于Component来说,是无需知道Decorator的存在的。至于ConcreteDecorator就是具体的装饰对象,起到给Component添加职责的功能。
装饰模式的具体代码:
#include<iostream>
#include<string>
usingnamespace std;
classComponent
{
public:
virtual void Operation()=0;
};
classConCreteComponent:virtual public Component
{
void Operation()
{
cout<<"具体对象的操作!"<<endl;
}
};
classDecorator:virtual public Component
{
public:
void setComponent(Component * component)
{
this->component=component;
}
void Operation()
{
component->Operation();
}
protected:
Component * component;
};
classConCreteDecoratorA:virtual public Decorator
{
public:
void Operation()
{
Decorator::Operation();
addedState="new state";
cout<<"装饰A的状态:"<<addedState<<endl;
cout<<"具体装饰A的操作"<<endl;
}
protected:
string addedState;
};
classConCreteDecoratorB:virtual public Decorator
{
public:
void Operation()
{
Decorator::Operation();
AddedBehavior();
cout<<"具体装饰B的操作"<<endl;
}
void AddedBehavior()
{
cout<<"B的行为"<<endl;
}
};
intmain()
{
ConCreteComponent *pc=newConCreteComponent();
ConCreteDecoratorA *pd1=newConCreteDecoratorA();
ConCreteDecoratorB *pd2=newConCreteDecoratorB();
pd1->setComponent(pc);
pd2->setComponent(pd1);
pd2->Operation();
delete pc;
delete pd1;
delete pd2;
return 0;
}
运行结果:
总结:
装饰模式提供了更加灵活的向对象添加职责的方式。可以用添加和分离的方法,用装饰在运行时刻增加和删除职责。装饰模式提供了一种“即用即付”的方
法来添加职责。它并不试图在一个复杂的可定制的类中支持所有可预见的特征,相反,你可以定义一个简单的类,并且用装饰类给它逐渐地添加功能。可以从简单的部件组合出复杂的功能。
实例:
#include<iostream>
#include<string>
usingnamespace std;
classPerson
{
public:
virtual void show()=0;
};
classMan :virtual public Person
{
public:
Man():name(NULL){}
Man(string name):name(name){}
void show()
{
cout<<name<<"先生:服装搭配:"<<endl;
}
private:
string name;
};
classWoman : virtual public Person
{
public:
Woman():name(NULL){}
Woman(string name):name(name){}
void show()
{
cout<<name<<"女士:服装搭配:"<<endl;
}
private:
string name;
};
classDecorator :virtual public Person
{
public:
void setComponent(Person * person)
{
this->person=person;
}
virtual void show()
{
if(person!=NULL)
person->show();
}
protected:
Person * person;
};
classDecoratorTs:virtual public Decorator
{
public:
void show()
{
Decorator::show();
cout<<" 搭配—t恤 "<<endl;
}
};
classDecoratorSk:virtual public Decorator
{
public:
void show()
{
Decorator::show();
cout<<" 搭配—球鞋 "<<endl;
}
};
classDecoratorNk:virtual public Decorator
{
public:
void Show()
{
Decorator::show();
cout<<" 搭配—牛仔裤 "<<endl;
}
};
intmain()
{
Man * pman=new Man("23k_bug");
DecoratorTs *pts=new DecoratorTs();
DecoratorSk *psk=new DecoratorSk();
DecoratorNk *pnk=new DecoratorNk();
pts->setComponent(pman);
psk->setComponent(pts);
pnk->setComponent(psk);
pnk->Show();
delete pman;
delete pts;
delete psk;
delete pnk;
return 0;
}