State状态模式


1. //先来一个状态:
2. package State;
3.
4. public abstract class State
5. {
6.
7. /** *//** Creates a new instance of State */
8. public State() {
9. }
10.
11. public abstract void opration(Context context);
12. }//end class State
13.
14. //在来两个具体的State:
15. public class ConcreteStateA extends State
16. {
17.
18. /** *//** Creates a new instance of ConcreteStateA */
19. public ConcreteStateA() {
20. }
21.
22. public void opration(Context context)
23. {
24. System.out.println("The Concrete A");
25. context.setSate(new ConcreteStateB());
26. }//end opration()
27.
28. public static ConcreteStateA getInstance()
29. {
30. return new ConcreteStateA();
31. }//end getInstance()
32. }
33.
34. public class ConcreteStateB extends State
35. {
36.
37. /** *//** Creates a new instance of ConcreteStateB */
38. public ConcreteStateB() {
39. }
40.
41. public void opration(Context context)
42. {
43. System.out.println("The Concrete B");
44. context.setSate(new ConcreteStateA());
45. }//end opration()
46.
47. public static ConcreteStateB getInstance()
48. {
49. return new ConcreteStateB();
50. }//end getInstance()
51.
52. }//end class ConcreteStateB
53.
54. //来一个场景:
55. public class Context
56. {
57. private State state;
58. /** *//** Creates a new instance of Context */
59. public Context() {
60. }
61.
62. public void setSate(State stat)
63. {
64. state = stat;
65. }//end setState()
66.
67. public void operation()
68. {
69. state.opration(this);
70. }//end operation()
71.
72. }//end class Context
73.
74. //怎样调用:
75. public static void main(String[] args)
76. {
77. Context con = new Context();
78. con.setSate(ConcreteStateA.getInstance());
79. con.operation();
80. con.operation();
81. }//end main()
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值