Objective C 语言 使用命令模式实现撤销操作

Objective-C阿木 发布于 2025-06-29 11 次阅读


摘要:

在软件开发中,撤销操作是一种常见的用户交互需求。命令模式(Command Pattern)是一种行为设计模式,它将请求封装为一个对象,从而允许用户对请求进行参数化、排队或记录请求,并支持可撤销的操作。本文将围绕Objective-C语言,探讨如何使用命令模式实现撤销操作。

一、

命令模式是一种结构型设计模式,它将请求封装为一个对象,从而允许用户对请求进行参数化、排队或记录请求,并支持可撤销的操作。在Objective-C中,命令模式可以用来实现撤销操作,使得用户可以撤销之前执行的操作。

二、命令模式的基本概念

命令模式包含以下角色:

1. 抽象命令(Command):定义执行操作的接口。

2. 具体命令(ConcreteCommand):实现抽象命令接口,封装对请求对象的操作。

3. 客户端(Client):创建具体命令对象,并设置接收者。

4. 接收者(Receiver):知道如何实施与执行一个请求相关的操作。

5. 调用者(Invoker):负责调用命令对象执行请求。

三、实现撤销操作

以下是一个使用命令模式实现撤销操作的示例:

1. 定义抽象命令

objective-c

@interface Command : NSObject

- (void)execute;


- (void)undo;

@end


2. 实现具体命令

objective-c

@interface MoveCommand : Command

@property (nonatomic, strong) Receiver receiver;


@property (nonatomic, strong) CGPoint startPoint;


@property (nonatomic, strong) CGPoint endPoint;

- (instancetype)initWithReceiver:(Receiver )receiver


startPoint:(CGPoint)startPoint


endPoint:(CGPoint)endPoint;

- (void)execute;


- (void)undo;

@end

@implementation MoveCommand

- (instancetype)initWithReceiver:(Receiver )receiver


startPoint:(CGPoint)startPoint


endPoint:(CGPoint)endPoint {


self = [super init];


if (self) {


_receiver = receiver;


_startPoint = startPoint;


_endPoint = endPoint;


}


return self;


}

- (void)execute {


[self.receiver moveFromPoint:self.startPoint toPoint:self.endPoint];


}

- (void)undo {


[self.receiver moveFromPoint:self.endPoint toPoint:self.startPoint];


}

@end


3. 实现接收者

objective-c

@interface Receiver : NSObject

- (void)moveFromPoint:(CGPoint)startPoint toPoint:(CGPoint)endPoint;

@end

@implementation Receiver

- (void)moveFromPoint:(CGPoint)startPoint toPoint:(CGPoint)endPoint {


// 实现移动操作


}

@end


4. 实现调用者

objective-c

@interface Invoker : NSObject

@property (nonatomic, strong) Command command;

- (void)setCommand:(Command )command;


- (void> executeCommand;


- (void)undoCommand;

@end

@implementation Invoker

- (void)setCommand:(Command )command {


_command = command;


}

- (void> executeCommand {


if (_command) {


[_command execute];


}


}

- (void)undoCommand {


if (_command) {


[_command undo];


}


}

@end


5. 使用命令模式实现撤销操作

objective-c

int main(int argc, const char argv[]) {


@autoreleasepool {


Receiver receiver = [[Receiver alloc] init];


CGPoint startPoint = CGPointMake(0, 0);


CGPoint endPoint = CGPointMake(100, 100);


MoveCommand command = [[MoveCommand alloc] initWithReceiver:receiver


startPoint:startPoint


endPoint:endPoint];


Invoker invoker = [[Invoker alloc] init];


[invoker setCommand:command];


[invoker executeCommand]; // 执行操作


[invoker undoCommand]; // 撤销操作


}


return 0;


}


四、总结

本文介绍了在Objective-C中使用命令模式实现撤销操作的方法。通过定义抽象命令、具体命令、接收者和调用者,我们可以将请求封装为一个对象,从而实现可撤销的操作。在实际开发中,命令模式可以应用于各种需要撤销操作的场景,提高代码的可读性和可维护性。