策略模式包含如下基本要素,策略基类,继承于基类的不同算法,包含策略引用的环境(context)角色
class vehicle;
class vehicle
{
public:
vehicle(){};
~vehicle(){};
virtual void showName()=0;
};
class bike:public vehicle
{
public:
bike(){};
~bike(){};
void showName()
{
std::cout<<"go by bike!"<<endl;
}
};
class car:public vehicle
{
public:
car(){};
~car(){};
void showName()
{
std::cout<<"go by car!"<<endl;
}
};
class trip
{
public:
trip(vehicle *pv):m_pv(pv){};
~trip()
{
delete m_pv;
m_pv = NULL;
};
void showVehicle()
{
m_pv->showName();
}
private:
vehicle * m_pv;
};
void main()
{
trip* t1 = new trip(new car());
t1->showVehicle();
cin.get();
}
当然也可以通过函数指针实现
typedef void(*pfun)(void);
void gobyBike()
{
std::cout<<"go by bike!"<<endl;
}
void gobycar()
{
std::cout<<"go by car!"<<endl;
}
class trip
{
public:
trip(pfun pf):mfunction(pf){};
~trip()
{
};
void showVehicle()
{
mfunction();
}
private:
pfun mfunction;
};
void main()
{
trip* t1 = new trip(gobycar);
t1->showVehicle();
delete t1;
cin.get();
}
忙里偷闲边看边练习一下