1 定义一个接口
2 public interface State {
3 public void handle();
4 }
5
6
7 /**
8 *具体的状态角色(下单)
9 * Created by Administrator
10 */
11 public class PlaceAnOrder implements State {
12 //具体化状态的行为
13 @Override
14 public void handle() {
15 Log.d("doAction","下单");
16 }
17 }
18
19 /**
20 *具体的状态角色(付款)
21 * Created by Administrator
22 */
23 public class PayTheOrder implements State {
24 @Override
25 public void handle() {
26 Log.d("doAction","付款");
27 }
28 }
29
30 /**
31 *具体的状态角色(发货)
32 * Created by Administrator
33 */
34 public class DeliverGoods implements State {
35 @Override
36 public void handle() {
37 Log.d("doAction","发货");
38 }
39 }
40
41 public class Context {
42 private State state;
43 public Context() {
44 }
45
46 public void setState(State state) {
47 this.state = state;
48 }
49
50 public void doAction() {
51 this.state.handle();
52 }
53 }
客户端调用
1 Context context=new Context();
2 //下单
3 State placeanOrder=new PlaceAnOrder();
4 context.setState(placeanOrder);
5 context.doAciton();
6
7 //付款
8 State paytheOrder=new PayTheOrder();
9 context.setState(paytheOrder);
10 context.doAciton();
11
12 //发货
13 State deliverGoods=new DeliverGoods();
14 context.setState(deliverGoods);
15 context.doAciton();