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. }  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值