Tuesday, May 4, 2010

Template Method : My example

We had several order events like – EnterOrder, SendOrder, CancelOrder etc.

We had 2 variations of the bzness logic in these events – one for UK and one for US.
So the class hierarchy was like this –
Base : EnterOrder
Derived1 : EnterOrderUK : public EnterOrder
Derived2 : EnterOrderUS : public EnterOrder

Base Class declaration is like this –
Class EnterOrder{
Public :
Run(){
Step1();
Step2();
Step3();
}
Private:
Virtual Step1(){}
Virtual Step2(){}
Virtual Step3(){}
};

Class EnterOrderUK{
Private :
Step1(){//UK specific code}
//other steps not overridden, so base class default functionality will be executed.
}

Class EnterOrderUS{
Private :
Step3(){//US specific code}
//other steps not overridden, so base class default functionality will be executed.
}

The code in main would be like this –
EnterOrder *ptr = NULL;
If(UK)
ptr= new EnterOrderUK();
Else (US)ptr = new EnterOrderUS();

Ptr->run();

Here, run in the base class is the only function my application has access to. This is a template algorithm, and functionality specific to derived classes will be overriden(step() functions).

No comments:

Post a Comment