物件中的物件/資料結構,可以是個參考或是獨立值。
值物件因不可變,所以較易理解和處理:外部物件在其改變時必會知道,整體設計也不需管理記憶體連結。

Change Reference to Value
這在分散(Distributed)與並行(Concurrent)系統特別好用,
但不適用於多物件引用同個物件,並想讓其變動都被其他物件看到的情境中。
flowchart TD
Q1{多個物件需要<br/>共享同一份資料?} -->|是| Ref["📎 使用 Reference<br/>(參考)"]
Q1 -->|否| Q2{資料會被修改?}
Q2 -->|否| Val["📦 使用 Value<br/>(值物件)"]
Q2 -->|是| Q3{需要追蹤變更<br/>傳播給其他物件?}
Q3 -->|是| Ref
Q3 -->|否| Val
Ref --> R1[適合:訂單與客戶關係]
Val --> V1[適合:日期、金額、座標]# Before
class Author:
def __init__(self, name):
self.name = name
def __repr__(self):
return f"Author({self.name})"
class Book:
def __init__(self, title, author):
self.title = title
self.author = author
def print_book_details(self):
print(f"Title: {self.title}, Author: {self.author}")
author = Author("George Orwell")
book = Book("1984", author)
# After
class Author:
def __init__(self, name):
self.name = name
def __repr__(self):
return f"Author({self.name})"
def __eq__(self, other):
if not isinstance(other, Author):
return NotImplemented
return self.name == other.name
def __hash__(self):
return hash(self.name)
class Book:
def __init__(self, title, author):
self.title = title
self.author = Author(author) # 建立新的值物件
def print_book_details(self):
print(f"Title: {self.title}, Author: {self.author}")
book = Book("1984", "George Orwell")