【设计模式】—— 状态模式State

  前言:【模式总览】——————————by xingoo

  模式意图

  允许一个对象在内部改变它的状态,并根据不同的状态有不同的操作行为。

  例如,水在固体、液体、气体是三种状态,但是展现在我们面前的确实不同的感觉。通过改变水的状态,就可以更改它的展现方式。

  应用场景

  1 当一个对象的行为,取决于它的状态时

  2 当类结构中存在大量的分支,并且每个分支内部的动作抽象相同,可以当做一种状态来执行时。

  模式结构

  

  Context 环境角色,里面包含状态对象

class Context{
    private State state;
    public void setState(State state) {
        this.state = state;
    }
    public void operation(){
        state.operation();
    }
}

  State 状态的抽象接口

interface State{
    public void operation();
}

  ConcreteState 具体的状态角色

class ConcreteState1 implements State{
    public void operation(){
        System.out.println("state1 operation");
    }
}
class ConcreteState2 implements State{
    public void operation(){
        System.out.println("state2 operation");
    }
}
class ConcreteState3 implements State{
    public void operation(){
        System.out.println("state3 operation");
    }
}

  全部代码

 1 package com.xingoo.test.design.state;
 2 class Context{
 3     private State state;
 4     public void setState(State state) {
 5         this.state = state;
 6     }
 7     public void operation(){
 8         state.operation();
 9     }
10 }
11 interface State{
12     public void operation();
13 }
14 class ConcreteState1 implements State{
15     public void operation(){
16         System.out.println("state1 operation");
17     }
18 }
19 class ConcreteState2 implements State{
20     public void operation(){
21         System.out.println("state2 operation");
22     }
23 }
24 class ConcreteState3 implements State{
25     public void operation(){
26         System.out.println("state3 operation");
27     }
28 }
29 public class Client {
30     public static void main(String[] args) {
31         Context ctx = new Context();
32         State state1 = new ConcreteState1();
33         State state2 = new ConcreteState2();
34         State state3 = new ConcreteState3();
35         
36         ctx.setState(state1);
37         ctx.operation();
38         
39         ctx.setState(state2);
40         ctx.operation();
41         
42         ctx.setState(state3);
43         ctx.operation();
44     }
45 }
View Code

  运行结果

state1 operation
state2 operation
state3 operation

 

posted @ 2014-11-09 11:58 xingoo 阅读(...) 评论(...) 编辑 收藏