C++下利用Command设计模式实现undo和redo


Command.hpp:


#ifndef _COMMAND_HPP
#define _COMMAND_HPP

#include <iostream>
#include <stack>
#include <string>

class Command
{
public:
	Command(){}
	virtual ~Command(){}

	virtual void Execute() = 0;
};


class InputCommand : public Command
{
	public:

		InputCommand( const std::string &input )
		{
			mInput = input;
		}
		~InputCommand()
		{}

		void Execute()
		{
			printf( "current string: %s\n", mInput.c_str() );
		}

private:

	std::string mInput;
};

class Commander
{
public:
	Commander( Command *pCmd )
	{
		//最初的命令数据
		mUndo.push( pCmd );
	}
	~Commander()
	{
		while( false == mUndo.empty() )
		{
			delete mUndo.top();
			mUndo.pop();
		}
		while( false == mRedo.empty() )
		{
			delete mRedo.top();
			mRedo.pop();
		}
	}
	
	void ExecuteCommand( Command *pCmd )
	{
		pCmd->Execute();
		mUndo.push( pCmd );
	}

	void Undo()
	{
		if( mUndo.size() < 2 
  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在Eclipse中,可以使用JFace的org.eclipse.jface.text包的undo/redo框架来实现对SWT组件的撤销/重做操作。以下是一个简单的示例代码,演示如何在Eclipse中对SWT Text组件进行撤销/重做操作: ```java import org.eclipse.jface.text.Document; import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.ITextOperationTarget; import org.eclipse.jface.text.ITextViewer; import org.eclipse.jface.text.TextViewerUndoManager; import org.eclipse.jface.text.source.SourceViewer; import org.eclipse.swt.SWT; import org.eclipse.swt.layout.FillLayout; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Text; public class SWTUndoRedoExample { public static void main(String[] args) { Display display = new Display(); Shell shell = new Shell(display); shell.setLayout(new FillLayout()); // 创建SWT Text组件 Text text = new Text(shell, SWT.BORDER | SWT.MULTI); // 创建SourceViewer控件 SourceViewer viewer = new SourceViewer(shell, null, SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL); IDocument document = new Document(); viewer.setDocument(document); // 将SWT Text组件设置为Viewer的文本输入目标 ITextOperationTarget target = (ITextOperationTarget) viewer; target.setTargetEditor(text); // 创建撤销/重做管理器并将其设置为Viewer的撤销/重做管理器 TextViewerUndoManager undoManager = new TextViewerUndoManager(20); viewer.setUndoManager(undoManager); // 显示窗口 shell.open(); while (!shell.isDisposed()) { if (!display.readAndDispatch()) { display.sleep(); } } display.dispose(); } } ``` 在上面的示例代码中,创建了一个SWT Text组件和一个SourceViewer控件,然后将SWT Text组件设置为Viewer的文本输入目标。接着创建了一个TextViewerUndoManager对象,并将其设置为Viewer的撤销/重做管理器。现在,当用户输入文本并按下Ctrl+Z或Ctrl+Y键时,就可以执行撤销/重做操作。 需要注意的是,撤销/重做操作只对文本输入产生影响。如果要在SWT组件中实现其他类型的撤销/重做操作,需要自己编写相应的代码。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值