跳去內容

物件組成

出自維基百科,自由嘅百科全書

物件組成英文object composition)係物件導向編程(OOP)上嘅一個概念,廣義上係泛指將啲物件或者資料類型砌埋一齊組成更加複雜嘅物件[1]

基礎

[編輯]

舉例說明,想像家陣有個人想編寫一個資訊系統程式,用嚟記住一間企業員工嘅個人資料,佢個程式可能會一段好似以下噉嘅 Python[2]

class Employee:
    def __init__(self, id, name):
        self.id = id
        self.name = name
        self.address = None

上述段碼做嘅係定義 Employee(員工)呢個類別,個類別由幾個特性、方法同物件組成,當中 address 可以係一件物件,又會有 street(街名)同 city(城市)等嘅組成部份[2]

物件結合

[編輯]

喺再進階啲嘅應用當中仲有所謂嘅物件結合(object aggregation):物件結合意思係指件複雜物件 com 由多件物件組成,但 com 並唔「擁有」啲組成部份-當 com 俾人剷走嗰陣,如果用嘅係物件組成,組成 com 啲物件都會跟住被剷走,但喺物件結合之下,啲組成部份並唔隸屬於 com,就算 com 俾人剷走,啲組成部份仲可以繼續噉存在。事實係有好多行 OOP 嘅程式語言都有陳述式專門做物件結合[1],例如想像一間大學又想整資訊系統記住啲員工嘅個資,可能會寫好似以下噉嘅 C++ 碼:

class Professor;  // Professor(教授)呢個類別喺個程式嘅第度定義咗,為咗慳篇幅呢度唔詳講。

class Department { // 定義 Department(部門)呢個類別...
  public:
    Department(const std::string& title): title_(title) {}

  private: // 物件結合:Professor 組成 Department 呢個類別,不過就算一個部門執咗,大學可能仲會想留住班教授同佢哋啲個資,調佢哋去第個部門。
    std::vector<std::weak_ptr<Professor>> members_;
    const std::string title_;
};

睇埋

[編輯]

參攷

[編輯]
  1. 1.0 1.1 Yaiser, Michelle. "Object-oriented programming concepts: Composition and aggregation". Archived from the original on April 8, 2015. There is a closely related concept to composition called aggregation. In conversation the differences between composition and aggregation are often ignored.
  2. 2.0 2.1 Composition in Python. Real Python.