例子:
class Pay
{
public:
virtual float CalculatePay()= 0;
};
class Commissioned:public Pay
{
public:
Commissioned(float fbasepay,float fcommission):_basePay(fbasepay),_commissionRate(fcommission)
{
}
float CalculatePay()
{
return _basePay*_commissionRate;
}
private:
float _basePay;
float _commissionRate;
};
class Salaried:public Pay
{
public:
Salaried(float fmonthlypay):_fmonthlypay(fmonthlypay)
{
}
float CalculatePay()
{
return _fmonthlypay;
}
private:
float _fmonthlypay;
};
class Hourly:public Pay
{
public:
Hourly(float fhourlyrate):_fhourlyrate(fhourlyrate)
{
}
float CalculatePay()
{
return _fhourlyrate;
}
private:
float _fhourlyrate;
};
class Employee
{
public:
Employee(int iid,CString strname):_iId(iid),_strName(strname),_pay(NULL)
{
}
//set the type of pay
void SetPayType(counst Pay* pPay)
{
if(_pay)
delete _pay;
if(pPay)
_pay = pPay;
}
float GetPay()
{
return _pay->CalculatePay();
}
private:
CString _strName;
int _iId;
Pay* _pay;
}
void main()
{
Vector<Employee> vect;
Employee e1(1,"e1");
e1.SetPayType (new Salaried(50));
vect.push_back(e1);
Employee e2(2,"e2");
e2.SetPayType (new Commissioned(50,0.8));
vect.push_back(e2);
Employee e3(3,"e3");
e3.SetPayType (new Hourly(4));
vect.push_back(e3);
float fTotal = 0;
for(int i = 0;i< vect.size();i++)
{
fTotal += ((Emplyee)vect[i]).GetPay();
}
}
调用者基本只和接口打交道,不和具体实现交互,这也体现了一个原则,面向接口编程,这样,以后增加第四个工资类型时,就不必修改调用者main中的代码了.
使用Command模式的一个好理由还因为它能实现Undo功能.每个具体命令都可以记住它刚刚执行的动作,并且在需要时恢复.
undo的代码等等再加!