MST

星途 面试题库

面试题:Objective-C 状态模式的基本实现

请用Objective-C代码实现一个简单的状态模式,假设有一个游戏角色,有“正常”“隐身”“加速”三种状态,每个状态下角色的移动速度不同,并且能在不同状态间切换。阐述实现思路并写出关键代码。
26.0万 热度难度
编程语言Objective-C

知识考点

AI 面试

面试题答案

一键面试

实现思路

  1. 定义一个状态基类,包含一个移动方法。
  2. 为每个具体状态创建子类,重写移动方法以实现不同的移动速度。
  3. 定义游戏角色类,包含当前状态属性,并提供切换状态的方法。

关键代码

// 状态基类
@interface CharacterState : NSObject
- (void)move;
@end

@implementation CharacterState
- (void)move {
    NSLog(@"默认移动速度");
}
@end

// 正常状态子类
@interface NormalState : CharacterState
@end

@implementation NormalState
- (void)move {
    NSLog(@"正常速度移动");
}
@end

// 隐身状态子类
@interface InvisibleState : CharacterState
@end

@implementation InvisibleState
- (void)move {
    NSLog(@"隐身时较慢速度移动");
}
@end

// 加速状态子类
@interface SpeedUpState : CharacterState
@end

@implementation SpeedUpState
- (void)move {
    NSLog(@"加速状态快速移动");
}
@end

// 游戏角色类
@interface GameCharacter : NSObject
@property (nonatomic, strong) CharacterState *currentState;

- (void)switchToState:(CharacterState *)state;
- (void)move;
@end

@implementation GameCharacter
- (void)switchToState:(CharacterState *)state {
    self.currentState = state;
}

- (void)move {
    [self.currentState move];
}
@end

使用示例

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        GameCharacter *character = [[GameCharacter alloc] init];
        [character switchToState:[[NormalState alloc] init]];
        [character move];
        
        [character switchToState:[[InvisibleState alloc] init]];
        [character move];
        
        [character switchToState:[[SpeedUpState alloc] init]];
        [character move];
    }
    return 0;
}