-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmobile.py
117 lines (89 loc) · 2.34 KB
/
mobile.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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
"""mobile state management system using state pattern
"""
class State:
"""state class for type hint
"""
name = 'null'
allowed = []
def switch(self):
"""switch to any state
"""
def add_allowed(self):
"""add state to allowed list
"""
class MobileState:
"""mobile state class
"""
name = 'state'
allowed = []
def switch(self, state: State):
"""switch to `state` if state is allowed
Args:
state (State): state of mobile
"""
if state.name in self.allowed:
print(f'Change "{self}" state to "{state.name}"')
self.__class__ = state # class change to `state`
else:
print(f'Impossible Change "{self}" to "{state.name}" state!')
@classmethod
def add_allowed(cls, state_name: str):
"""add state to allowed list
Args:
state_name (str): state name
"""
cls.allowed.append(state_name)
def __str__(self):
return self.name
class Off(MobileState):
"""Mobile Off Mode
"""
name = "Off"
allowed = ['On']
class On(MobileState):
"""Mobile On Mode
"""
name = "On"
allowed = ['Off', 'Restart', 'Airplane']
class Restart(MobileState):
"""Mobile Restart Mode
"""
name = "Restart"
allowed = ['On']
class Airplane(MobileState):
"""Mobile Airplane Mode
"""
name = "Airplane"
allowed = ['On', 'Off', 'Restart']
class MobileManagement:
"""mobile management class
"""
def __init__(self, model='SAMSUNG'):
self.model = model
# default state
self.state = Off()
def change(self, state: MobileState):
"""change mobile state to `state`
Args:
state (MobileState): new mobile state
"""
self.state.switch(state)
def get_state(self) -> str:
"""get current mobile state
Returns:
str: mobile state
"""
return self.state.name
if __name__ == "__main__":
mobile = MobileManagement()
mobile.change(On)
mobile.change(Off)
mobile.change(Restart)
mobile.change(On)
mobile.change(Restart)
mobile.change(On)
mobile.change(Airplane)
Off.add_allowed("Restart")
mobile.change(Off)
mobile.change(Restart)
print("Current State is", mobile.get_state())