实现思路
- 定义一个状态基类,包含一个移动方法。
- 为每个具体状态创建子类,重写移动方法以实现不同的移动速度。
- 定义游戏角色类,包含当前状态属性,并提供切换状态的方法。
关键代码
// 状态基类
@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;
}