命令模式封装一个请求或行为作为一个对象。封装的请求比原的更加灵活,可以在对象之间传递,储存,动态修改,或放入一个队列。
那么让我们简要的说一下命令模式的特点。
下面给出基本的类结构图:
上面这张图是命令模式的类结构的基本图。其实从这张图中还可以扩展出很多,细节就不说了,给大家留一些想象的空间,呵呵!
还是老规矩,下面给出实例:
Objective-C 示例:
Command:
#import <Foundation/Foundation.h>
@interface NimoReceiver : NSObject
- (void)action;
@end
#import "NimoReceiver.h"
@implementation NimoReceiver
- (void)action
{
NSLog(@"实际执行");
}
@end
#import <Foundation/Foundation.h>
#import "NimoReceiver.h"
#import "NimoInvoker.h"
#import "NimoConcreteCommand.h"
int main(int argc, const char * argv[]) {
@autoreleasepool {
NimoReceiver *receiver = [[NimoReceiver alloc] init];
NimoConcreteCommand *command = [[NimoConcreteCommand alloc] initWithReceiver:receiver];
NimoInvoker *invoker = [[NimoInvoker alloc] init];
invoker.command = command;
[invoker executeCommand];
}
return 0;
}
2015-08-13 22:49:56.412 CommandDemo[1385:43303] 实际执行
Cocoa Touch框架中的命令模式:
NSInvocation对象
如下示例,Client没有直接调用Receiver的方法,而是用NSInvocation对象封装了运行时库向Receiver发送执行消息所需的所有必要信息,这里的NSInvocation对象类似于上文中的ConcreteCommand对象。
Receiver:
#import <Foundation/Foundation.h>
@interface NimoReceiver : NSObject
- (int)printWithName:(NSString *)name gender:(NSString *)gender age:(int)age;
@end
#import "NimoReceiver.h"
@implementation NimoReceiver
- (int)printWithName:(NSString *)name gender:(NSString *)gender age:(int)age
{
NSLog(@"My name is %@, %@, %d years old.", name, gender, age);
return 119;
}
@end
#import <Foundation/Foundation.h>
#import "NimoReceiver.h"
int main(int argc, const char * argv[]) {
@autoreleasepool {
//用Receiver的实例创建NSInvocation对象,并把Receiver的action作为选择器
NimoReceiver *receiver = [[NimoReceiver alloc] init];
NSString *name = @"Lee";
NSString *gender = @"male";
int age = 28;
SEL sel = @selector(printWithName:gender:age:);
NSMethodSignature *methodSignature = [[receiver class] instanceMethodSignatureForSelector:sel];
NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:methodSignature];
[invocation setTarget:receiver];
[invocation setSelector:sel];
[invocation setArgument:&name atIndex:2];
[invocation setArgument:&gender atIndex:3];
[invocation setArgument:&age atIndex:4];
[invocation retainArguments];
[invocation invoke]; //通过调用NSInvocation对象的invoke方法,完成对Receiver中action的调用
int returnValue = 0;
[invocation getReturnValue:&returnValue];
NSLog(@"returnValue: %d", returnValue);
}
return 0;
}
2015-08-14 13:37:44.162 InvocationDemo[1049:36632] My name is Lee, male, 28 years old.2015-08-14 13:37:44.164 InvocationDemo[1049:36632] returnValue: 119
其实,单从类关系图中可以简单的看出,命令模式其实是把需求(Invoker)和具体实现(Receiver)通过命令层(Command)进行了解耦。具体实现过程根据不同的命令进行了区分。
新闻热点
疑难解答