State

Introduction

The state pattern allows an object to alter its behavior when its internal state changes. The object will appear to change its class. And the UML graph is similar to Strategy pattern.

Example

Last weekend, I watched a F1 match. And noticed that Hamilton ran into an issue when starting because the car’s start mode button did not work. A conspiracy?

Also I noticed that there is a burst mode of the engine that driveres can use to get much more power with a little more fuel.

So here I take car as an example as I always take the things I am familar with. Normally, a car has three modes: start mode, normal mode and burst mode. As a state pattern, it is easy to add other modes, so auto mode is added to my fancy car because of Google’s advanced unmaned technology. I wish there is a fly mode in the near future :(

Code

Cpp

As there are two classes referenced with each other, to pass build we need to split header file and cpp file.