banner
Aug 2, 2023
55 Views

State pattern

Written by
banner

Mẫu trạng thái là một mẫu thiết kế phần mềm hành vi cho phép một đối tượng thay đổi hành vi của nó khi trạng thái nội tại của nó thay đổi. Mẫu trạng thái có thể được hiểu như một mẫu chiến lược, cho phép chuyển đổi chiến lược thông qua việc gọi các phương thức được định nghĩa trong giao diện của mẫu.

The state pattern is a behavioral software design pattern that allows an object to alter its behavior when its internal state changes. This pattern is close to the concept of finite-state machines. The state pattern can be interpreted as a strategy pattern, which is able to switch a strategy through invocations of methods defined in the pattern's interface.

Ví dụ: giả sử chúng ta có hệ thống đèn giao thông đơn giản. Đèn giao thông có ba trạng thái: "Đỏ," "Vàng," và "Xanh." Hành vi của đèn giao thông thay đổi dựa trên trạng thái hiện tại. Khi đèn "Đỏ," nó dừng giao thông; khi đèn "Vàng," nó chuẩn bị chuyển đổi tín hiệu; và khi đèn "Xanh," nó cho phép giao thông tiếp tục đi.

# Define the Traffic Light states
class RedLightState:
    def __str__(self):
        return "Red Light"

    def next_state(self):
        return GreenLightState()


class YellowLightState:
    def __str__(self):
        return "Yellow Light"

    def next_state(self):
        return RedLightState()


class GreenLightState:
    def __str__(self):
        return "Green Light"

    def next_state(self):
        return YellowLightState()


# Context class to manage the Traffic Light
class TrafficLight:
    def __init__(self):
        self._state = RedLightState()

    def change_state(self):
        self._state = self._state.next_state()

    def show_current_state(self):
        print(f"Current State: {self._state}")


# Example usage
if __name__ == "__main__":
    traffic_light = TrafficLight()

    for _ in range(5):
        traffic_light.show_current_state()
        traffic_light.change_state()
Article Categories:
dev
banner

Comments to State pattern

  • Quá hay, nhưng sẽ tuyệt vời hơn với 1 ví dụ thực tế =))

    BigFan September 10, 2023 18:19 Reply

Leave a Reply

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