zno2

21) State pattern

类别:

 Behavioral Pattern

问题:

 

方案:

 

示例:

public class StatePatternDemo {
    public static void main(String[] args) {
        Context context = new Context();
        context.fight();
        context.setState(new Super());
        context.fight();
    }
}

interface State {
    void fight(Context context);

    String getName();
}

class Context {
    private State state;

    public Context() {
        setState(new Normal());
    }

    void setState(State state) {
        System.out.println("The state now is:" + state.getName());
        this.state = state;
    }

    public void fight() {
        state.fight(this);
    }
}

class Normal implements State {
    @Override
    public void fight(Context context) {
        System.out.println("↓↘→+A(百八式·暗勾手)");
    }

    @Override
    public String getName() {
        return "Normal";
    }
}

class Super implements State {

    @Override
    public void fight(Context context) {
        System.out.println("↓↙←↙↓↘→+A(里百八式·八酒杯)");
    }

    @Override
    public String getName() {
        return "Super";
    }
}

 

The state now is:Normal
↓↘→+A(百八式·暗勾手)
The state now is:Super
↓↙←↙↓↘→+A(里百八式·八酒杯)

 

应用:

 

不足:(

 

优化:)

 

posted on 2023-06-09 13:36  zno2  阅读(7)  评论(0编辑  收藏  举报

导航