state.py 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. """Implementation of the state pattern"""
  2. # http://ginstrom.com/scribbles/2007/10/08/design-patterns-python-style/
  3. class State(object):
  4. """Base state. This is to share functionality"""
  5. def scan(self):
  6. """Scan the dial to the next station"""
  7. self.pos += 1
  8. if self.pos == len(self.stations):
  9. self.pos = 0
  10. print("Scanning... Station is", self.stations[self.pos], self.name)
  11. class AmState(State):
  12. def __init__(self, radio):
  13. self.radio = radio
  14. self.stations = ["1250", "1380", "1510"]
  15. self.pos = 0
  16. self.name = "AM"
  17. def toggle_amfm(self):
  18. print("Switching to FM")
  19. self.radio.state = self.radio.fmstate
  20. class FmState(State):
  21. def __init__(self, radio):
  22. self.radio = radio
  23. self.stations = ["81.3", "89.1", "103.9"]
  24. self.pos = 0
  25. self.name = "FM"
  26. def toggle_amfm(self):
  27. print("Switching to AM")
  28. self.radio.state = self.radio.amstate
  29. class Radio(object):
  30. """A radio. It has a scan button, and an AM/FM toggle switch."""
  31. def __init__(self):
  32. """We have an AM state and an FM state"""
  33. self.amstate = AmState(self)
  34. self.fmstate = FmState(self)
  35. self.state = self.amstate
  36. def toggle_amfm(self):
  37. self.state.toggle_amfm()
  38. def scan(self):
  39. self.state.scan()
  40. # Test our radio out
  41. if __name__ == '__main__':
  42. radio = Radio()
  43. actions = [radio.scan] * 2 + [radio.toggle_amfm] + [radio.scan] * 2
  44. actions *= 2
  45. for action in actions:
  46. action()
  47. ### OUTPUT ###
  48. # Scanning... Station is 1380 AM
  49. # Scanning... Station is 1510 AM
  50. # Switching to FM
  51. # Scanning... Station is 89.1 FM
  52. # Scanning... Station is 103.9 FM
  53. # Scanning... Station is 81.3 FM
  54. # Scanning... Station is 89.1 FM
  55. # Switching to AM
  56. # Scanning... Station is 1250 AM
  57. # Scanning... Station is 1380 AM