声明命令接口类
@protocol CommandProtocol <NSObject>
- (void)execute;
@end
声明&实现一个具体命令类
@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
命令发送者类
@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];
如此便实现了命令发送者和接受者的完全解耦,二者只要通过命令对象来联系。不管接受者如何变化,只需要改变命令调用者的命令关联对象即可。客户端是面向命令调用者编程的,所以也不需要修改。