Java Learning Note-design mode 21 (state mode)

Source: Internet
Author: User

Intention

Allows an object to change its behavior when its internal state changes. The object appears to have modified its class.

public class State {            private String value;            Public String GetValue () {          return value;      }        public void SetValue (String value) {          this.value = value;      }        public void Method1 () {          System.out.println ("Execute the first opt!");      }            public void Method2 () {          System.out.println ("Execute the second opt!");      }  }  

  

public class Context {        private state State;        Public Context {          this.state = state;      }        Public State getState () {          return state;      }        public void SetState (state state) {          this.state = state;      }        public void Method () {          if (State.getvalue (). Equals ("State1")) {              state.method1 ();          } else if ( State.getvalue (). Equals ("State2")) {              state.method2 ();          }      }  

  

public class Test {public        static void Main (string[] args) {state state                    = new State ();          Context context = new context (state);                    Set the first state          state.setvalue ("State1");          Context.method ();                    Set the second state          state.setvalue ("State2");          Context.method ();      }  

  

Transferred from: http://blog.csdn.net/zhangerqing/article/details/8245537

Java Learning Note-design mode 21 (state mode)

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.