标签:
命令模式:将请求封装为一个对象,从而可用不同的请求对客户进行参数化,对请求排队或记录请求日志,以及支持可撤销的操作。
Command: 为Invoker所知的通用接口(协议)
ConcreteCommand: 具体的命令对象,将Receiver(执行者)与action(实际操作)进行绑定
Receiver: 执行实际操作的对象
Invoker: 命令调用者,接收通用命令
Objective-C 示例:
Command:
// // NimoCommand.h // CommandDemo // // Created by Tony on 15/8/13. // Copyright (c) 2015年 NimoWorks. All rights reserved. // #import <Foundation/Foundation.h> @protocol NimoCommand <NSObject> - (void)execute; @end
ConcreteCommand:
// // NimoConcreteCommand.h // CommandDemo // // Created by Tony on 15/8/13. // Copyright (c) 2015年 NimoWorks. All rights reserved. // #import <Foundation/Foundation.h> #import "NimoCommand.h" @class NimoReceiver; @interface NimoConcreteCommand : NSObject <NimoCommand> @property (nonatomic) NimoReceiver *receiver; - (id)initWithReceiver:(NimoReceiver *)receiver; @end
//
// NimoConcreteCommand.m
// CommandDemo
//
// Created by Tony on 15/8/13.
// Copyright (c) 2015年 NimoWorks. All rights reserved.
//
#import "NimoConcreteCommand.h"
#import "NimoReceiver.h"
@implementation NimoConcreteCommand
- (void)execute
{
[_receiver action];
}
- (id)initWithReceiver:(NimoReceiver *)receiver
{
if (self = [super init]) {
_receiver = receiver;
}
return self;
}
@end
Receiver:
// // NimoReceiver.h // CommandDemo // // Created by Tony on 15/8/13. // Copyright (c) 2015年 NimoWorks. All rights reserved. // #import <Foundation/Foundation.h> @interface NimoReceiver : NSObject - (void)action; @end
//
// NimoReceiver.m
// CommandDemo
//
// Created by Tony on 15/8/13.
// Copyright (c) 2015年 NimoWorks. All rights reserved.
//
#import "NimoReceiver.h"
@implementation NimoReceiver
- (void)action
{
NSLog(@"实际执行");
}
@end
Invoker:
// // NimoInvoker.h // CommandDemo // // Created by Tony on 15/8/13. // Copyright (c) 2015年 NimoWorks. All rights reserved. // #import <Foundation/Foundation.h> #import "NimoCommand.h" @interface NimoInvoker : NSObject @property (nonatomic, weak) id<NimoCommand> command; - (void)executeCommand; @end
//
// NimoInvoker.m
// CommandDemo
//
// Created by Tony on 15/8/13.
// Copyright (c) 2015年 NimoWorks. All rights reserved.
//
#import "NimoInvoker.h"
@implementation NimoInvoker
- (void)executeCommand
{
[_command execute];
}
@end
Client:
//
// main.m
// CommandDemo
//
// Created by Tony on 15/8/13.
// Copyright (c) 2015年 NimoWorks. All rights reserved.
//
#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;
}
Running:
2015-08-13 22:49:56.412 CommandDemo[1385:43303] 实际执行
标签:
原文地址:http://my.oschina.net/fuzheng/blog/492088