状态模式的使用方法 [英] State pattern using methods

查看:70
本文介绍了状态模式的使用方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试基于状态模式的修改版本来实现一个简单的状态机,该状态机将方法用作状态而不是类,就像这样:

I'm trying to implement a simple state machine based on a modified version of the state pattern using methods as states instead of classes, something like this:

private Action<Input> currentState;
private void NextState(Input i) {
    currentState(i);
}

private void State1(Input i) {
    if( i ... )
        currentState = State1;
    else
        currentState = State2;
}

private void State2(Input i) {
    if( i ... )
        currentState = State1;
    else
        currentState = State2;  
}

但是如果可以的话,它会更加优雅:

But it would be more elegant if I could do:

private void NextState(Input i) {
    currentState = currentState(i);
}

private Func<xxx> State1() {
    if( i ... )
        return State1;
    else
        return State2;
}

但是我不知道怎么写这个Func.有办法吗?

But I don't know how to write this Func. Is there a way to do this?

推荐答案

如果要使用返回void的函数,请尝试使用 Action .

If you want to use functions which return void, try using Action instead.

private Action State1() {
    if( ... )
        return State1Inner;
    else
        return State2Inner;
}

如果要使用返回带有其自身签名的函数的函数,则必须首先定义一个自定义委托类型.这是通用版本:

If you want to use a function which returns a function with it's own signature, you have to define a custom delegate type first. Here's a generic version:

public delegate State<T> State<T>(T input);

private State<int> State1(int input) {
    if( ... )
        return State1;
    else
        return State2;
}

这将帮助您避免具有内部状态功能.

This will help you avoid having inner state functions.

这篇关于状态模式的使用方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆