標籤:
命令模式:將請求封裝為一個對象,從而可用不同的請求對客戶進行參數化,對請求排隊或記錄請求日誌,以及支援可撤銷的操作。
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] 實際執行
iOS設計模式---命令模式(未完)