banner
Jun 19, 2023
95 Views

Decorator pattern

Written by
banner

The decorator pattern is a design pattern that allows behavior to be added to an individual object, dynamically, without affecting the behavior of other objects from the same class.

Decorator là một mẫu thiết kế hành vi cho phép thêm hành vi vào một đối tượng cụ thể một cách linh hoạt, mà không ảnh hưởng đến hành vi của các đối tượng khác thuộc cùng một lớp.

Ví dụ: bạn thích uống trà sữa và bạn đã có 1 class pha trà, giờ thêm hành vi đổ thêm sữa là thành trà sữa. Lúc này chúng ta implement như sau:

# Define a base component interface or class
class Tea:
    def operation(self):
        pass

# Create a concrete component class
class OLongTea(Tea):
    def operation(self):
        print("Making O Long tea.")

# Create a decorator class that wraps a component
class Decorator(Tea):
    def __init__(self, component):
        self.component = component

    def operation(self):
        self.component.operation()

# Create concrete decorator classes that add additional behavior
class TraSuaTranChau(Decorator):
    def operation(self):
        super().operation()
        self.added_behavior()

    def added_behavior(self):
        print("Add Tran Chau.")

class TraSuaLanh(Decorator):
    def operation(self):
        super().operation()
        self.added_behavior()

    def added_behavior(self):
        print("Add Ice Cubes.")

# Usage
component = OLongTea()
decoratorA = TraSuaTranChau(component)

""" OUTPUT
Making O Long tea.
Add Tran Chau.
"""
decoratorA.operation()



decoratorB = TraSuaLanh(decoratorA)
""" OUTPUT
Making O Long tea.
Add Tran Chau.
Add Ice Cubes.
"""
decoratorB .operation()
Article Categories:
dev
banner

Leave a Reply

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