example:
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: Hourly (Float Fhourlyrate): _fhourlyrate (fhourryrate) {} float calculate () {return_fhourlyrate;} private: float_fhourty
Class Employee {Public: Employee (int IID, CSTRING STRNAME): _ IID (IID), _ strname (strname), _ pay (null) {} // set the type} {if (_pay) {if (_pay) DELETE _PAY; if (pPAY) _PAY = PPAY;} Float getPay () {return_pay-> CalculatePay ();} private: cstring _strname; int _iid; pay * _pay;}
Void main () {Vector
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 The caller is basically only dealing with the interface, not interacting with the specific implementation, which also reflects a principle that interface programming, so that when adding the fourth salary type, it is not necessary to modify the code in the caller main. A good reason to use the Command mode is also because it can implement the UNDO function. Each specific command can remember the action it just execute and recovered when needed. Undo code, etc.