banner
Jun 17, 2023
94 Views

Composite pattern

Written by
banner

The composite pattern describes a group of objects that are treated the same way as a single instance of the same type of object. The intent of a composite is to "compose" objects into tree structures to represent part-whole hierarchies. Implementing the composite pattern lets clients treat individual objects and compositions uniformly.

Mô hình composite mô tả một nhóm đối tượng được xử lý theo cùng một cách như một phiên bản của loại đối tượng đó. Mục đích của một composite là "tổng hợp" các đối tượng thành cấu trúc cây để biểu diễn các hệ thống phân cấp. Triển khai mô hình composite cho phép các khách hàng xử lý các đối tượng cá nhân và tổng hợp một cách đồng đều.

Ví dụ: bạn có cấu trúc thư mục-file. Mỗi lần duyệt cây thư mục bạn muốn hiển thị theo như cách bạn vẫn quen thuộc trên các trình quản lý file khác. Bạn có thể implement như sau:

class FileSystemElement:
    def operation(self):
        raise NotImplementedError()

class File(FileSystemElement):
    def __init__(self, name):
        self.name = name

    def operation(self):
        print(f"Performing operation on file: {self.name}")

class Directory(FileSystemElement):
    def __init__(self, name):
        self.name = name
        self.children = []

    def add(self, element):
        self.children.append(element)

    def remove(self, element):
        self.children.remove(element)

    def operation(self):
        print(f"Performing operation on directory: {self.name}")
        for child in self.children:
            child.operation()

# Usage example
root = Directory("Root")
dir1 = Directory("Dir1")
dir2 = Directory("Dir2")
file1 = File("File1")
file2 = File("File2")
file3 = File("File3")

root.add(dir1)
root.add(dir2)
dir1.add(file1)
dir2.add(file2)
dir2.add(file3)

root.operation()

""" OUTPUT
Performing operation on directory: Root
Performing operation on directory: Dir1
Performing operation on file: File1
Performing operation on directory: Dir2
Performing operation on file: File2
Performing operation on file: File3
"""
Article Categories:
dev
banner

Leave a Reply

Your email address will not be published. Required fields are marked *