聲明命令接口類
@protocol CommandProtocol <NSObject>
- (void)execute;
@end
聲明&實現(xiàn)一個具體命令類
@interface ZDWLogNameConcreteCommand : NSObject <CommandProtocol>
- (instancetype)initWithReceiver:(ZDWUser *)receiver;
@end
@implementation ZDWLogNameConcreteCommand
- (instancetype)initWithReceiver:(ZDWUser *)receiver {
if (self = [super init]) {
self.user = receiver;
}
return self;
}
#pragma mark - CommandProtocol
- (void)execute {
[self.user logName];
}
@end
命令接受者類
@interface ZDWUser : NSObject
- (void)logName;
@end
@implementation ZDWUser
- (void)logName {
NSLog(@"%@",NSStringFromClass([ZDWUser class]));
}
@end
命令發(fā)送者類
@interface ZDWCommandInvoker : NSObject
@property (nonatomic, weak) id<CommandProtocol> command;
- (void)sendCommand;
@end
@implementation ZDWCommandInvoker
- (void)sendCommand {
[self.command execute];
}
@end
Client
ZDWUser *user = [ZDWUser new];
ZDWLogNameConcreteCommand *command = [[ZDWLogNameConcreteCommand alloc] initWithReceiver:user];
ZDWCommandInvoker *invoker = [[ZDWCommandInvoker alloc] init];
invoker.command = command;
[invoker sendCommand];
如此便實現(xiàn)了命令發(fā)送者和接受者的完全解耦肤视,二者只要通過命令對象來聯(lián)系徙赢。不管接受者如何變化字柠,只需要改變命令調(diào)用者的命令關(guān)聯(lián)對象即可〗拼停客戶端是面向命令調(diào)用者編程的窑业,所以也不需要修改。