0

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.

jaco0646
  • 15,303
  • 7
  • 59
  • 83
Sisyphus
  • 900
  • 12
  • 32
  • This looks very homeworky. You should try something and then tell us of any problems you may have, rather than asking us to do it for you – Mattsjo Aug 30 '13 at 13:32
  • i have killed it searching for a neat solution but couldn't find any! – Sisyphus Aug 30 '13 at 13:35

1 Answers1

0

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.

Mattsjo
  • 627
  • 5
  • 11
  • This only works for the simple scenario above, that's why i have written the P.S. line at the bottom. But what if we have 10 states with 2 operations with Operation1 having 4 different implmentations, states from 1 to 3 uses an implementation of Operation1, states 4 to 6 uses another implemntation, states 7 and 8 uses another, and state 9 and 10 uses another? – Sisyphus Aug 30 '13 at 17:06