定义
将一个请求封装成一个对象,从而让用户使用不同的请求把客户端参数化;对请求排队或记录日志,以及支持可撤销的操作。
场景
- 要将各种执行的动作抽象出来,使用时通过不同的参数来决定执行哪个对象
- 某个或某些操作要支持撤销的场景
- 某个操作要支持事务操作的时候
- 要对操作过程记录日志,以便后期通过日志将操作过程重新做一遍时
实现
1、UML图
2、使用
- 构建Command协议,统一Command执行操作
@protocol Command <NSObject>
-(void)execute;
@end
- 构建具体的命令
@interface CopyCommand : NSObject<Command>
@property(nonatomic,strong)CopyReceiver *receive;
-(instancetype)initWithCopyReceiver:(CopyReceiver*)receive;
@end
#import "CopyCommand.h"
@implementation CopyCommand
- (instancetype)initWithCopyReceiver:(CopyReceiver *)receive
{
self = [super init];
if (self) {
self.receive = receive;
}
return self;
}
- (void)execute{
[self.receive copyAction];
}
@end
@interface DeleteCommand : NSObject<Command>
@property(nonatomic, strong)DeleteReceiver *receiver;
-(instancetype)initWithDeleteReceive:(DeleteReceiver *)receiver;
@end
#import "DeleteCommand.h"
@implementation DeleteCommand
- (instancetype)initWithDeleteReceive:(DeleteReceiver *)receiver
{
self = [super init];
if (self) {
self.receiver = receiver;
}
return self;
}
- (void)execute{
[self.receiver deleteAction];
}
@end
- 构建命令接收器
@interface CopyReceiver : NSObject
-(void)copyAction;
@end
#import "CopyReceiver.h"
@implementation CopyReceiver
- (void)copyAction{
NSLog(@"copy action");
}
@end
@interface DeleteReceiver : NSObject
-(void)deleteAction;
@end
#import "DeleteReceiver.h"
@implementation DeleteReceiver
- (void)deleteAction{
NSLog(@"delete action");
}
@end
- invoke:负责按照客户端的指令设置并执行命令
@interface Invoke : NSObject
-(void)addCommand:(id<Command>)command;
-(void)clearCommand;
-(void)executeCommand;
@end
#import "Invoke.h"
@interface Invoke()
@property(nonatomic, strong)NSMutableArray *commands;
@end
@implementation Invoke
- (instancetype)init
{
self = [super init];
if (self) {
self.commands = [[NSMutableArray alloc] init];
}
return self;
}
- (void)addCommand:(id<Command>)command{
[self.commands addObject:command];
}
- (void)clearCommand{
[self.commands removeAllObjects];
}
- (void)executeCommand{
for(id<Command> command in self.commands)
{
[command execute];
}
}
@end
client调用
Invoke *invoke = [[Invoke alloc] init];
//每个命令都需绑定一个接收器
CopyReceiver *copyReceiver = [[CopyReceiver alloc] init];
CopyCommand *copyCommand = [[CopyCommand alloc] initWithCopyReceiver:copyReceiver];
[invoke addCommand:copyCommand];
DeleteReceiver *deleteReceiver = [[DeleteReceiver alloc] init];
DeleteCommand *deleteCommand = [[DeleteCommand alloc] initWithDeleteReceive:deleteReceiver];
[invoke addCommand:deleteCommand];
[invoke executeCommand];
总结
- 一个请求一个命令,有多少请求,就有多少命令
- Invoker类只认识接口Command
- 客户端类负责生成命令,并通过invoker组装执行
代码
链接: https://pan.baidu.com/s/1eoOP6IPvJDeMwVThVoe3Nw 提取码: j0s3