#include<iostream>
using namespace std;
class CarHandle
{
public:
virtual void HandleCar() = 0;
CarHandle *setCarHandle(CarHandle*carhandle)
{
m_carhandle = carhandle;
return m_carhandle;
}
protected:
CarHandle *m_carhandle;//用来指向下一个环节
};
class HeadCarHandle :public CarHandle
{
public:
virtual void HandleCar()
{
cout << "造车身" << endl;
if (m_carhandle != NULL)
{
m_carhandle->HandleCar();
}
}
};
class BodyCarHandle :public CarHandle
{
public:
virtual void HandleCar()
{
cout << "造车身" << endl;
if (m_carhandle != NULL)
{
m_carhandle->HandleCar();
}
}
};
class TailCarHandle :public CarHandle
{
public:
virtual void HandleCar()
{
cout << "造车尾" << endl;
if (m_carhandle != NULL)
{
m_carhandle->HandleCar();
}
}
};
void main()
{
HeadCarHandle *headcarhandle = new HeadCarHandle;
BodyCarHandle *bodycarhandle = new BodyCarHandle;
TailCarHandle *tailcarhandle = new TailCarHandle;
headcarhandle->setCarHandle(bodycarhandle);
bodycarhandle->setCarHandle(tailcarhandle);
tailcarhandle->setCarHandle(NULL);
headcarhandle->HandleCar();
delete headcarhandle;
delete bodycarhandle;
delete tailcarhandle;
}
运行结果: