Status mode example

Source: Internet
Author: User
1. The State mode allows an "object" to change its behavior when its internal state changes.
2. Status mode roles:
Abstract state, specific State (usually several, with different behaviors under each State), environment (context) role (that is, the state of an object, generally, this object needs to initialize a state, change the state, and behavior in this state)

When we play basketball, athletes can be in normal, abnormal, and extraordinary states. Now we will take the status when we play basketball as an example,

First, we abstract the state and its behavior,
Interface State {
Public void shot ();
}
Then implement the specific state. Here we have three and three States.
Abnormal
Public class nonormalstate implements State {
Public void shot (){
System. Out. println ("Today you shot ten times ");
}
}
Normal:
Public class normalstate implements State {
Public void shot (){
System. Out. println ("Today you shot five in ten ");
}
}
Extraordinary:
Public class superstate implements State {
Public void shot (){
System. Out. println ("You shot ten shots today ");
}
}
At this time, we come to an environment where an athlete is normal.
Public class player {
Private state = new normalstate ();
Public void setstate (State state ){
This. State = State;
}
Public void shot (){
State. Shot (); // here I feel like an Object Adapter IN THE create mode. This should be the case,
}
}
Test this example
Public class statetest
{
Public static void main (string [] ARGs ){
Player player = new player ();
Player. Shot (); // shooting normally
Player. setstate (New nonormalstate ());
Player. Shot (); not shooting normally
Player. setstate (new superstate ());
Player. Shot (); shooting under extraordinary circumstances
}
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.