banner
Oct 5, 2023
51 Views

Visitor pattern

Written by
banner

Một mẫu thiết kế Visitor là một mẫu thiết kế phần mềm tách biệt thuật toán khỏi cấu trúc đối tượng. Do sự tách rời này, các hoạt động mới có thể được thêm vào cấu trúc đối tượng hiện có mà không cần sửa đổi cấu trúc. Đây là một trong những cách thực hiện nguyên tắc mở/rộng (open/closed principle) trong lập trình hướng đối tượng và kỹ thuật phần mềm.

A visitor pattern is a software design pattern that separates the algorithm from the object structure. Because of this separation new operations can be added to existing object structures without modifying the structures. It is one way to follow the open/closed principle in object-oriented programming and software engineering.

Ví dụ khi bạn làm phần mềm tính toán các thông số của người lao động gồm 2 kiểu là Nhân viên và Quản lý.

# Define the Visitor interface
class EmployeeVisitor:
    def visit_employee(self, employee):
        pass

    def visit_manager(self, manager):
        pass

# Define concrete visitors
class SalaryCalculator(EmployeeVisitor):
    def __init__(self):
        self.total_salary = 0

    def visit_employee(self, employee):
        self.total_salary += employee.salary

    def visit_manager(self, manager):
        self.total_salary += manager.salary

class VacationDaysCalculator(EmployeeVisitor):
    def __init__(self):
        self.total_vacation_days = 0

    def visit_employee(self, employee):
        self.total_vacation_days += employee.vacation_days

    def visit_manager(self, manager):
        self.total_vacation_days += manager.vacation_days

# Define the employee hierarchy
class Employee:
    def __init__(self, name, salary, vacation_days):
        self.name = name
        self.salary = salary
        self.vacation_days = vacation_days

    def accept(self, visitor):
        visitor.visit_employee(self)

class Manager(Employee):
    def __init__(self, name, salary, vacation_days, team_size):
        super().__init__(name, salary, vacation_days)
        self.team_size = team_size

    def accept(self, visitor):
        visitor.visit_manager(self)

# Client code
if __name__ == "__main__":
    employees = [
        Employee("John Doe", 50000, 10),
        Manager("Alice Smith", 80000, 15, 5),
        Employee("Bob Johnson", 60000, 12),
    ]

    salary_calculator = SalaryCalculator()
    vacation_days_calculator = VacationDaysCalculator()

    for employee in employees:
        employee.accept(salary_calculator)
        employee.accept(vacation_days_calculator)

    print(f"Total Salary: ${salary_calculator.total_salary}")
    print(f"Total Vacation Days: {vacation_days_calculator.total_vacation_days}")

Article Categories:
config · dev
banner

Leave a Reply

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