O'Reilly logo

Learning PHP Design Patterns by William Sanders

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Chapter 10. The State Design Pattern

Could the young but realize how soon they will become mere walking bundles of habits, they would give more heed to their conduct while in the plastic state.

William James

In each action we must look beyond the action at our past, present, and future state, and at others whom it affects, and see the relations of all those things. And then we shall be very cautious.

Blaise Pascal

All our final decisions are made in a state of mind that is not going to last.

Marcel Proust

What Is the State Pattern?

The State design pattern is one of the most intriguing and useful patterns of those devised by GoF. Games often depend on the State pattern because objects can change states so frequently in games. The purpose of the State pattern is to allow an object to change its behavior when the state changes. Many other simulations, whether they are games or not, depend on the State pattern as well; you will find many uses for it, as this chapter demonstrates. Figure 10-1 shows the basic design pattern in a class diagram.

State design pattern class diagram
Figure 10-1. State design pattern class diagram

As shown, there’s no Client class; however, GoF note that the Context is the primary interface for the clients. When examining the pattern, think of the Client class making its request through the Context class. There’s a lot to understanding and effectively using the State design pattern, so for now, just ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required