可以把一系列动作封装成一个命令,在用户不需要知道其实现细节,使用细节的情况下就可以调用。
一般在想让应用程序支持撤销与恢复的情况下使用这一模式。
在OC中NSInvocation和NSUndoManager是这个模式的两个实现。
NSInvocation
使用方法:
NSMethodSignature *signature = [[self class] instanceMethodSignatureForSelector:@selector(run:)];
NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:signature];
[invocation setTarget:self];
[invocation setSelector:@selector(run:)];
NSString *str = @"haha";
int d;
[invocation setArgument:&str atIndex:2];
[invocation invoke];
[invocation getReturnValue:&d];
NSLog(@"%d",d);
- (int) run:(NSString *) str{
NSLog(@"run:%@",str);
return 1;
}
NSUndoManager
工作原理:
当进行操作时,控制器会添加一个该操作的逆操作的invocation到Undo栈中。当进行Undo操作时,Undo操作的逆操作会倍添加到Redo栈中,就这样利用Undo和Redo两个堆栈巧妙的实现撤销操作。
undoManager的两个栈里面保存的都是invocation对象.
- (void) method1{
// [[self.undoManager prepareWithInvocationTarget:self] run];
[self.undoManager registerUndoWithTarget:self selector:@selector(run) object:nil];
}
- (void) method2{
[self.undoManager undo];
}
其中 run 是一个undo的方法。
每次执行method1的时候就注册一个undo方法到栈里面。
然后每次执行undo的时候就会调用run方法。
method1中两个注册undo方法的方式都可以运行。