Computer Science Design Patterns/State

{{Computer Science Design Patterns/Page Allow an object to alter its behaviour when its internal state changes. The object will appear to change its class.
 * mode={{{mode|reading}}}
 * page={{{page|{{SUBPAGENAME}}}}}
 * stage=25
 * stage date=31 December 2014
 * stage comment=Add more illustrations.
 * previous=Singleton
 * next=Strategy
 * content=

{{Java/Hidden begin|title=Implementation in C#}} {{Hidden end}}

{{Java/Hidden begin|title=Implementation in Java}} The state interface and two implementations. The state's method has a reference to the context object and is able to change its state.

The context class has a state variable that it instantiates in an initial state, in this case. In its method, it uses the corresponding methods of the state object.

The test below shows also the usage:

According to the above code, the output of main from TestClientState should be:

monday TUESDAY WEDNESDAY thursday FRIDAY SATURDAY sunday {{Hidden end}}

{{Java/Hidden begin|title=Implementation in Perl}} {{Hidden end}}

{{Java/Hidden begin|title=Implementation in Python}} According to the above Perl and Python code, the output of main should be:

Scanning... Station is 1250 AM Scanning... Station is 1380 AM Switching to FM Scanning... Station is 81.3 FM Scanning... Station is 89.1 FM Scanning... Station is 103.9 FM Scanning... Station is 81.3 FM Switching to AM Scanning... Station is 1510 AM Scanning... Station is 1250 AM {{Hidden end}}

{{Java/Hidden begin|title=Implementation in Ruby}} In the Ruby example below, a radio can switch to two states AM and FM and has a scan button to switch to the next station.

{{Hidden end}}

{{Java/Hidden begin|title=Implementation in Hack}} The state interface and two implementations. The state's method has a reference to the context object and is able to change its state.

The context class has a state variable that it instantiates in an initial state, in this case. In its method, it uses the corresponding methods of the state object.

The test below shows also the usage:

According to the above code, the output of main entry point should be:

monday TUESDAY WEDNESDAY thursday FRIDAY SATURDAY sunday {{Hidden end}}