State Pattern

It's possible for some objects to behave completely differently when they are in different states. Let's think about an easy example first. Consider rendering and interacting with a custom button in two states: enabled and disabled. When the button is enabled, it lights up and changes its style to active on a mouse hover, and of course, it handles clicks; when disabled, it dims and no longer cares about mouse events.

We may think of an abstraction with two operations: render (with a parameter that indicates whether the mouse is hovering) and click; along with two states: enabled and disabled. We can even divide deeper and have state active, but that won't be necessary in our case.

And now we can have StateEnabled with both render ...

Get TypeScript Design Patterns now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.