EasyText, EasyLicense 的作者, https://github.com/EasyHelper Good Good Study,Day Day Up.

 

Head First 设计模式中的命令模式 的一个错误

最近在看Head First 设计模式,其中命令模式中有讲到实现撤销功能,并且作者还出了一道题,

 

下面的是书中习题:

public class MarcoCommand implements Command
{
	Command[] commands;
	public MarcoCommand(Command[] commands)
	{
		this.commands = commands;
	}
	public void execute()
	{
		for (int i = 0; i < commands.Length; i++)
		{
			commands[i].execute();
		}
	}
	public void undo()
	{ 
		//请实现撤销功能。
	}
}

 

在看到这里的时候,其实脑子里已经完成了答案了,可是最后看到书后面的答案的时候,却感觉有点奇怪,仔细想想还有点意思.

书中的答案如下:

public class MarcoCommand implements Command
{
	Command[] commands;
	public MarcoCommand(Command[] commands)
	{
		this.commands = commands;
	}
	public void execute()
	{
		for (int i = 0; i < commands.Length; i++)
		{
			commands[i].execute();
		}
	}
	public void undo()
	{ 
		for (int i = 0; i < commands.Length; i++)
		{
			commands[i].undo();
		}
	}
}

 

你看出这段代码的问题了吗?

posted @ 2012-11-19 21:38  LoveJenny  阅读(1754)  评论(13编辑  收藏  举报
EasyText, EasyLicense 的作者, https://github.com/EasyHelper Good Good Study,Day Day Up.