Php Chinese network (www.php.cn) provides the most comprehensive basic tutorial on programming technology, introducing HTML, CSS, Javascript, Python, Java, Ruby, C, PHP, basic knowledge of MySQL and other programming languages. At the same time, this site also provides a large number of online instances, through which you can better learn programming... The State mode is a behavior mode that allows an object to change its behavior when its internal state changes. The object seems to have modified its class. the State mode changes in the object state.
Primary role
Abstract State role: defines an interface to encapsulate behaviors corresponding to a specific State of an environmental object.
ConcreteState role: each state class implements a behavior corresponding to a state of the environment (Context ).
Context role: defines the interface that the client is interested in and retains an instance of a specific status class. The instance of this specific status class shows the existing status of the environment object
Applicability
The behavior of an object depends on its state, and it must change its behavior according to its state at runtime.
An operation contains a large number of conditional statements with multiple branches, and these branches depend on the state of the object. This state is usually represented by one or more enumerated constants. Generally, multiple operations contain the same condition structure. In State mode, each condition branch is placed in an independent class. This allows you to take the state of the object as an object in the case of the object itself. this object can be independent of other objects.
Class diagram
Instance
SetState (ConcreteStateB: getInstance () ;}} class ConcreteStateB implements State {// role B private static $ _ instance = null; private function _ construct () {} public static function getInstance () {if (is_null (self ::: _ instance) {self ::$ _ instance = new ConcreteStateB ();} return self :: $ _ instance;} public function handle (Context $ context) {$ context-> setState (ConcreteStateA: getInstance () ;}} c Lass Context {// environment role private $ _ state; public function _ construct () {// The default value is stateA $ this-> _ state = ConcreteStateA: getInstance ();} public function setState (State $ state) {$ this-> _ state = $ state;} public function request () {$ this-> _ state-> handle ($ this) ;}// client $ context = new Context (); $ context-> request (); $ context-> request ();?>
Advantages and disadvantages
Advantages
It will localize behaviors related to specific states
It makes the status transition display
The State object can be shared.