装饰器模式
动态地给一个对象添加一些额外的工作职责,就增加功能来说,装饰器模式比继承的子类更灵活。
装饰模式的类结构图:
兑现代码:
#include <string>
#include <iostream>
using namespace std;
class Car
{
public:
virtual void showcar()=0;
};
class RunCar:public Car
{
public:
void showcar()
{
cout<<"Run..."<<endl;
}
};
class SwimCarDe:public Car
{
public:
SwimCarDe(Car*car)
{
m_car=car;
}
void showcar()
{
m_car->showcar();
cout<<"swim..."<<endl;
}
private:
Car *m_car;
};
class FlyCarDe:public Car
{
public:
FlyCarDe(Car*car)
{
m_car=car;
}
void showcar()
{
m_car->showcar();
cout<<"fly..."<<endl;
}
private:
Car *m_car;
};
void main04()
{
Car *c = NULL;
c = new RunCar();
c->showcar();
/*SwimCarDe*sc =new SwimCarDe(c);
sc->showcar();*/
SwimCarDe *sc =new SwimCarDe(c);
sc->showcar();
FlyCarDe *fc =new FlyCarDe(sc);
fc->showcar();
/*别忘了释放对象*/
delete fc;
delete sc;
delete c;
cout<<"nihao..."<<endl;
system("pause");
return ;
}