定义
当一个对象内在状态改变时允许改变其行为,这个对象看起来像是改变了其类
场景
代码中有很长的if else分支,分支都是不同状态下执行的操作不一样。
实现
1、UML图
状态模式.png
2、使用
- 构建状态协议,统一状态对象操作
@protocol StateProtocol <NSObject>
-(void)doAction;
@end
@interface State : NSObject<StateProtocol>
@end
#import "State.h"
@implementation State
-(void)doAction{
NSLog(@"do action normal, please use subclass");
}
@end
2、构建具体状态类,执行具体状态操作
@interface State1 : State
@end
#import "State1.h"
@implementation State1
- (void)doAction{
NSLog(@"doAction state1");
}
@end
#import "State.h"
NS_ASSUME_NONNULL_BEGIN
@interface State2 : State
@end
#import "State2.h"
@implementation State2
- (void)doAction{
NSLog(@"doAction State2");
}
@end
3、状态的切换及保存类
#import "State.h"
NS_ASSUME_NONNULL_BEGIN
@interface Context : NSObject
@property(nonatomic, strong)State *state;
-(void)doAction;
@end
#import "Context.h"
@implementation Context
- (void)doAction{
if(self.state){
[self.state doAction];
}
}
@end
4、Client调用
Context *context = [[Context alloc] init];
State *state1 = [[State1 alloc] init];
context.state = state1;
[context doAction];
State *state2 = [[State2 alloc] init];
context.state = state2;
[context doAction];
总结
- 增强了程序的可扩展性,很容易扩展新的State类
- 增强了程序的封装性,状态对应的操作都封装到了一个类中
状态模式与策略模式
- 策略模式是同一个任务有多种算法
- 状态模式是不同的状态执行不同的任务
代码
链接: https://pan.baidu.com/s/1fHAvgfbXbHG5OY1pq5l-Dw 提取码: 6d83