Common behavior in State Pattern states

127 views Asked by At

You have an ATM Machine with 3 states and 2 methods. if this is a phesudo implemntation of the pattern.

01-- class AbstractATMState
02-- Operation1
03-- Operation2
04--
05-- class State1 : AbstractATMState
06-- Operation1
07-- Operation2
08-- 
09-- class State2 : AbstractATMState
10-- Operation1
11-- Operation2
12-- 
13-- class State3 : AbstractATMState
14-- Operation1
15-- Operation2

If Operation1 has the same behavior for the 3 states, you will simply put the implementation at Operation1 at line 02, but what if Operation1 has the same implementation for only 2 states and a different implementation for the third? how would you solve this problem without repeating your code?

P.S. this is a very simplified example of the situation of course, but the same concept will go on say 40 states with 7 operations to be implemented.

1

There are 1 answers

1
Mattsjo On

Put the definition for Operation1 in AbstractATMState and override it in State3.

Put it in line 2 but then put a different implementation in line 14. When you call it from State3 it'll use linearisation (look it up if you want) to get the most appropriate version, which is the one in its own class if it exists, not the base class. But it'll take the base class version for State1 and State2 so you wouldn't need to give them their own implementations.