Skip to content

Commit cb01719

Browse files
committed
🔧 Adding
State Design Pattern
1 parent b6f7890 commit cb01719

File tree

1 file changed

+82
-0
lines changed

1 file changed

+82
-0
lines changed
Lines changed: 82 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,82 @@
1+
from abc import ABC, abstractmethod
2+
3+
4+
# -------------- STATE INTERFACE ----------------
5+
class State(ABC):
6+
def __init__(self, document):
7+
self.document = document
8+
9+
@abstractmethod
10+
def edit(self):
11+
...
12+
13+
@abstractmethod
14+
def publish(self, user_role: str):
15+
...
16+
17+
18+
# -------------- CONCRETE STATES ----------------
19+
class DraftState(State):
20+
def edit(self):
21+
print("[Draft] You can freely edit the document.")
22+
23+
def publish(self, user_role: str):
24+
print("[Draft] Moving to moderation.")
25+
self.document.change_state(ModerationState(self.document))
26+
27+
28+
class ModerationState(State):
29+
def edit(self):
30+
print("[Moderation] Document is under review. Limited editing allowed.")
31+
32+
def publish(self, user_role: str):
33+
if user_role.lower() == "admin":
34+
print("[Moderation] Approved by admin. Document is now published.")
35+
self.document.change_state(PublishedState(self.document))
36+
else:
37+
print("[Moderation] Only admins can publish from moderation.")
38+
39+
40+
class PublishedState(State):
41+
def edit(self):
42+
print("[Published] Cannot edit a published document.")
43+
44+
def publish(self, user_role: str):
45+
print("[Published] Document is already published. No action taken.")
46+
47+
48+
# -------------- CONTEXT ----------------
49+
class Document:
50+
def __init__(self):
51+
self._state: State = DraftState(self)
52+
print("[Document] Initialized in Draft state.")
53+
54+
def change_state(self, new_state: State):
55+
self._state = new_state
56+
print(f"[Document] State changed to {self._state.__class__.__name__}.")
57+
58+
def edit(self):
59+
self._state.edit()
60+
61+
def publish(self, user_role: str):
62+
self._state.publish(user_role)
63+
64+
65+
# -------------- CLIENT CODE ----------------
66+
def main():
67+
document = Document()
68+
69+
document.edit() # Allowed
70+
document.publish("writer") # Moves to Moderation
71+
72+
document.edit() # Limited edit
73+
document.publish("user") # Denied (not admin)
74+
75+
document.publish("admin") # Published
76+
77+
document.edit() # Not allowed
78+
document.publish("admin") # Already published
79+
80+
81+
if __name__ == "__main__":
82+
main()

0 commit comments

Comments
 (0)