Command模式实现的简单文本编辑器
这是一个基于Command设计模式实现的一个简单文本编辑器,在文本编辑器中可以根据指定命令去对编辑器中存储的字符串进行操作,目前实现的命令有:复制、粘贴、删除、改变字体颜色、大小写转换、删除空格、文本反转、插入日期命令。以下是编写步骤。
1. 编写Command命令接口和CommandHistory命令历史记录类
//命令接口
public interface Command {
void execute();
void undo();
}
// 命令历史记录类
public class CommandHistory {
private final List<Command> history = new ArrayList<>();
void execute(Command command) {
command.execute();
history.add(command);
}
void undoLastCommand() {
if (!history.isEmpty()) {
Command lastCommand = history.remove(history.size() - 1);
lastCommand.undo();
}
}
}
2. 编写8个对应的Command实现类
2.1. 复制命令
//复制命令
public class CopyCommand implements Command {
private final String text;
private final StringBuilder clipboard;
public CopyCommand(String text, StringBuilder clipboard) {
this.text = text;
this.clipboard = clipboard;
}
public void execute() {
clipboard.setLength(0); // 清空剪切板
clipboard.append(text);
}
public void undo() {
clipboard.setLength(0); // 清空剪切板
}
}
2.2. 粘贴命令
//粘贴命令
public class PasteCommand implements Command {
private final int position;
private final StringBuilder clipboard;
private final StringBuilder content;
public PasteCommand(int position, StringBuilder clipboard, StringBuilder content) {
this.position = position;
this.clipboard = clipboard;
this.content = content;
}
public void execute() {
content.insert(position, clipboard);
}
public void undo() {
content.delete(position, position + clipboard.length());
}
}
2.3. 删除命令
// 删除命令
public class DeleteCommand implements Command {
private final int start;
private final int end;
private final StringBuilder content;
private String deletedText;
public DeleteCommand(int start, int end, StringBuilder content) {
this.start = start