在目标C中使用枚举实现状态机

时间:2014-05-22 14:11:03

标签: objective-c enums

我需要在objective-c中实现状态机,就像这个java代码一样:

public enum State {

    INITIAL {
        @Override
        State doSomething(String aParameter) {
            System.out.println("Doing Something in INITIAL state and jumping to NEXT_STEP, argument = " + aParameter);
            return NEXT_STEP;
        }
    },
    NEXT_STEP {
        @Override
        State doSomething(String aParameter) {
            System.out.println("Doing Something in NEXT_STEP and jumping into FINAL, argument = " + aParameter);
            return FINAL;
        }
    },
    FINAL {
        @Override
        State doSomething(String aParameter) {
            System.out.println("I am in FINAL state, argument = " + aParameter);
            return this;
        }
    };

    abstract State doSomething(String aParameter);
}

参考链接是: http://www.mirkosertic.de/doku.php/javastuff/enumstatemachine

有人可以给我一些建议吗?

1 个答案:

答案 0 :(得分:1)

感谢所收到的信息,并根据我的需要...

我希望找到最佳解决方案,然后分享:

文件StateHandler.h:

enum State {
    INITIAL,
    NEXT_STEP,
    FINAL
};

@interface StateHandler

+(enum State)doSomething:(NSString *)aParameter withState:(enum State)state;

@end

文件StateHandler.m:

#import "StateHandler.h"

@protocol StateProtocol <NSObject>
@required +(enum State)doSomething:(NSString *)aParameter;
@end

@interface StateInitial : NSObject <StateProtocol>
@end

@interface StateNextStep : NSObject <StateProtocol>
@end

@interface StateFinal : NSObject <StateProtocol>
@end

@implementation StateHandler

+(enum State)doSomething:(NSString *)aParameter withState:(enum State)state {
    switch(state) {
        case INITIAL:
            return [StateInitial doSomething:aParameter];

        case NEXT_STEP:
            return [StateNextStep doSomething:aParameter];

        case FINAL:
            return [StateFinal doSomething:aParameter];
    }
}
@end

@implementation StateInitial
+(enum State)doSomething:(NSString *)aParameter {
    NSLog(@"Doing Something in INITIAL state and jumping to NEXT_STEP, argument = %@", aParameter);
    return NEXT_STEP;
}
@end

@implementation StateNextStep
+(enum State)doSomething:(NSString *)aParameter {
    NSLog(@"Doing Something in NEXT_STEP and jumping into FINAL, argument = %@", aParameter);
    return FINAL;
}
@end

@implementation StateFinal
+(enum State)doSomething:(NSString *)aParameter {
    NSLog(@"I am in FINAL state, argument = %@", aParameter);
    return FINAL;
}
@end