-
-
Notifications
You must be signed in to change notification settings - Fork 125
/
state_concept.py
53 lines (41 loc) · 1.28 KB
/
state_concept.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# pylint: disable=too-few-public-methods
"The State Pattern Concept"
from abc import ABCMeta, abstractmethod
import random
class Context():
"This is the object whose behavior will change"
def __init__(self):
self.state_handles = [ConcreteStateA(),
ConcreteStateB(),
ConcreteStateC()]
self.handle = None
def request(self):
"""A method of the state that dynamically changes which
class it uses depending on the value of self.handle"""
self.handle = self.state_handles[random.randint(0, 2)]
return self.handle
class IState(metaclass=ABCMeta):
"A State Interface"
@staticmethod
@abstractmethod
def __str__():
"Set the default method"
class ConcreteStateA(IState):
"A ConcreteState Subclass"
def __str__(self):
return "I am ConcreteStateA"
class ConcreteStateB(IState):
"A ConcreteState Subclass"
def __str__(self):
return "I am ConcreteStateB"
class ConcreteStateC(IState):
"A ConcreteState Subclass"
def __str__(self):
return "I am ConcreteStateC"
# The Client
CONTEXT = Context()
print(CONTEXT.request())
print(CONTEXT.request())
print(CONTEXT.request())
print(CONTEXT.request())
print(CONTEXT.request())