Java设计模式之状态模式

STATE (Object Behavioral) 
Purpose 
Ties object circumstances to its behavior, allowing the object 
to behave in different ways based upon its internal state. 
Use When 
    1 The behavior of an object should be influenced by its state. 
    2 Complex conditions tie object behavior to its state. 
    3 Transitions between states need to be explicit. 
Example 
An email object can have various states, all of which will 
change how the object handles different functions. If the state 
is “not sent” then the call to send() is going to send the message 
while a call to recallMessage() will either throw an error or do 
nothing. However, if the state is “sent” then the call to send() 
would either throw an error or do nothing while the call to 
recallMessage() would attempt to send a recall notification 
to recipients. To avoid conditional statements in most or all 
methods there would be multiple state objects that handle the 
implementation with respect to their particular state. The calls 
within the Email object would then be delegated down to the 
appropriate state object for handling. 

Java代码 
  1. package javaPattern.state;  
  2.   
  3. public interface State {  
  4.     public void handle(Context context);  
  5. }  
  6.   
  7. class ConcreteStateA implements State{  
  8.   
  9.     @Override  
  10.     public void handle(Context context) {  
  11.         //在A中设置B状态  
  12.         context.setState(new ConcreteStateB());  
  13.     }  
  14.       
  15. }  
  16. class ConcreteStateB implements State{  
  17.   
  18.     @Override  
  19.     public void handle(Context context) {  
  20.         //在B中设置A状态  
  21.         context.setState(new ConcreteStateA());  
  22.     }  
  23.       
  24. }  
  25. class Context {  
  26.     private State state;  
  27.   
  28.     public State getState() {  
  29.         return state;  
  30.     }  
  31.   
  32.     public void setState(State state) {  
  33.         this.state = state;  
  34.         System.out.println("当前设置的状态是"+state.getClass().getName());  
  35.     }  
  36.   
  37.     public Context(State state) {  
  38.         this.state = state;  
  39.     }  
  40.     public void request(){  
  41.         this.state.handle(this);  
  42.     }  
  43.     public static void main(String[] args) {  
  44.         Context context = new Context(new ConcreteStateA());  
  45.         context.request();  
  46.     }  
  47.       
  48. }  

你可能感兴趣的:(java,设计模式)