當某資料結構被用時,大都檢查其中某值並採同樣行動,
用特例元素就能把這類情境換成簡單呼叫式。

Introduce Special Case
特例能有多種方式呈現:
| 情境 | 做法 |
|---|---|
| 某物件只會被讀取 | 設為物件常值(Literal),放入所需值 |
| 需要存值還要其他行為 | 建立一個特殊物件來包含 |
| 空值處理 | Null Object 就是種特例 |
# Before
class Customer:
def __init__(self, name, plan, is_active):
self.name = name
self.plan = plan
self.is_active = is_active
def get_billing_plan(self):
if not self.is_active:
return "basic"
return self.plan
# After
class Customer:
def __init__(self, name, plan, is_active):
self.name = name
self.plan = plan
self.is_active = is_active
def get_billing_plan(self):
return self.plan
class InactiveCustomer(Customer):
def __init__(self):
super().__init__(name="N/A", plan="basic", is_active=False)
def get_billing_plan(self):
return "basic"
active_customer = Customer("Alice", "premium", True)
inactive_customer = InactiveCustomer()