State Pattern

noun

say it: “STAYT PAT-urn” /steɪt ˈpætərn/

A design pattern that gives each state an object can be in its own class, so the object hands every request to its current state, which decides what is allowed and which state comes next.

What is the State pattern?

The State pattern gives each state an object can be in its own class. The object hands every request to its current state, which answers what's allowed from there and which state comes next, so no method has to check a status word. A package that's shipped can be loaded but not canceled, and a new status is one new class.

class Canceled:
    name = "canceled"


class Ordered:
    name = "ordered"

    def cancel(self):  # an ordered package may be canceled
        return Canceled()


print(Ordered().cancel().name)  # canceled

In a sentence

  • “With the State pattern, held at the depot was one new class, and the other statuses didn't change.”
  • “Every method checked the package's status until we switched to the State pattern.”

Level: Freelancer · More OOP terms at this level

Updated