Chan Chen Coding...

Eight: State Design Pattern

State Design Pattern is mainly for changing state at run-time.

The Java example below shows how State pattern works.

The idea behind the example: people normally work harder when they are poor and play more when they are rich. What they do depends on the state in which they are.

Here is the class diagram. You can compare this with strategy pattern to get better understanding of the difference.

State classes.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
package com.programcreek.designpatterns.state;
 
interface State {
   public void saySomething(StateContext sc);
}
 
class Rich implements State{
   @Override
   public void saySomething(StateContext sc) {
      System.out.println("I'm rick currently, and play a lot.");
      sc.changeState(new Poor());
   }
}
 
class Poor implements State{
   @Override
   public void saySomething(StateContext sc) {
      System.out.println("I'm poor currently, and spend much time working.");
      sc.changeState(new Rich());
   }
}

StateContext class

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
package com.programcreek.designpatterns.state;
 
public class StateContext {
   private State currentState;
    
   public StateContext(){
      currentState = new Poor();
   }
    
   public void changeState(State newState){
      this.currentState = newState;
   }
    
   public void saySomething(){
      this.currentState.saySomething(this);
   }
}

Main class for testing

1
2
3
4
5
6
7
8
9
10
11
import com.programcreek.designpatterns.*;
 
public class Main {
   public static void main(String args[]){
      StateContext sc = new StateContext();
      sc.saySomething();
      sc.saySomething();
      sc.saySomething();
      sc.saySomething();
   }
}

Result:

1
2
3
4
I'm poor currently, and spend much time working.
I'm rick currently, and play a lot.
I'm poor currently, and spend much time working.
I'm rick currently, and play a lot.


-----------------------------------------------------
Silence, the way to avoid many problems;
Smile, the way to solve many problems;

posted on 2012-11-02 14:56 Chan Chen 阅读(309) 评论(0)  编辑  收藏 所属分类: Design Pattern


只有注册用户登录后才能发表评论。


网站导航: