將函式封裝成命令物件有時很有用,它大多僅有一種方法,其功能就是對這方法的請求與執行。

Replace Function with Command
相比於一般函式,命令更加靈活,但也會帶來更多複雜度。
flowchart TD
Q1{需要以下功能?} --> Q2{Undo/Redo<br/>撤銷/重做}
Q1 --> Q3{延遲執行<br/>Queue}
Q1 --> Q4{複雜參數<br/>共享狀態}
Q1 --> Q5{生命週期<br/>管理}
Q2 -->|是| Cmd["🎯 使用 Command<br/>命令物件"]
Q3 -->|是| Cmd
Q4 -->|是| Cmd
Q5 -->|是| Cmd
Q2 -->|否| Q3
Q3 -->|否| Q4
Q4 -->|否| Q5
Q5 -->|否| Func["⚡ 使用 Function<br/>一般函式"]通常選擇函式即可,在簡單作法仍無法提供所需功能時才改用命令。
# Before
def print_details(name, age):
print(f"Name: {name}, Age: {age}")
print_details("Alice", 30)
# After
class PrintDetailsCommand:
def __init__(self, name, age):
self.name = name
self.age = age
def execute(self):
print(f"Name: {self.name}, Age: {self.age}")
cmd = PrintDetailsCommand("Alice", 30)
cmd.execute()