Python Design Patterns Tutorial
Python Design Patterns Resources
Selected Reading
- Exception Handling
- Python Design Patterns - Anti
- Concurrency in Python
- Strings & Serialization
- Python Design Patterns - Queues
- Python Design Patterns - Sets
- Lists Data Structure
- Dictionaries
- Python Design Patterns - Iterator
- Object Oriented Concepts Implementation
- Object Oriented
- Abstract Factory
- Python Design Patterns - Flyweight
- Python Design Patterns - Template
- Python Design Patterns - Strategy
- Python Design Patterns - State
- Python Design Patterns - Observer
- Chain of Responsibility Pattern
- Python Design Patterns - Proxy
- Python Design Patterns - Decorator
- Python Design Patterns - Adapter
- Python Design Patterns - Command
- Python Design Patterns - Facade
- Python Design Patterns - Prototype
- Python Design Patterns - Builder
- Python Design Patterns - Factory
- Python Design Patterns - Singleton
- Model View Controller Pattern
- Python Design Patterns - Gist
- Introduction
- Python Design Patterns - Home
Python Design Patterns Resources
Selected Reading
- Who is Who
- Computer Glossary
- HR Interview Questions
- Effective Resume Writing
- Questions and Answers
- UPSC IAS Exams Notes
Python Design Patterns - State
Python Design Patterns - State
It provides a module for state machines, which are implemented using subclasses, derived from a specified state machine class. The methods are state independent and cause transitions declared using decorators.
How to implement the state pattern?
The basic implementation of state pattern is shown below −
class ComputerState(object): name = "state" allowed = [] def switch(self, state): """ Switch to new state """ if state.name in self.allowed: print Current: ,self, => switched to new state ,state.name self.__class__ = state else: print Current: ,self, => switching to ,state.name, not possible. def __str__(self): return self.name class Off(ComputerState): name = "off" allowed = [ on ] class On(ComputerState): """ State of being powered on and working """ name = "on" allowed = [ off , suspend , hibernate ] class Suspend(ComputerState): """ State of being in suspended mode after switched on """ name = "suspend" allowed = [ on ] class Hibernate(ComputerState): """ State of being in hibernation after powered on """ name = "hibernate" allowed = [ on ] class Computer(object): """ A class representing a computer """ def __init__(self, model= HP ): self.model = model # State of the computer - default is off. self.state = Off() def change(self, state): """ Change state """ self.state.switch(state) if __name__ == "__main__": comp = Computer() comp.change(On) comp.change(Off) comp.change(On) comp.change(Suspend) comp.change(Hibernate) comp.change(On) comp.change(Off)
Output
The above program generates the following output −
Advertisements