TW Assignment的代码实现

<span style="font-family: Arial, Helvetica, sans-serif; background-color: rgb(255, 255, 255);">这几天练习设计模式,在网上看到了thoughtworks的一道Assignment,地址:</span><a target=_blank target="_blank" href="http://blog.sina.com.cn/s/blog_6ffe0cc10100yeon.html" style="font-family: Arial, Helvetica, sans-serif; background-color: rgb(255, 255, 255);">点击打开链接</a>


【原题】:

A squad of robotic rovers are to be landed by NASA on a plateau on Mars.

This plateau, which is curiously rectangular, must be navigated by the rovers so that their on-board cameras can get a complete view of the surrounding terrain to send back to Earth.

A rover's position and location is represented by a combination of x and y co-ordinates and a letter representing one of the four cardinal compass points. The plateau is divided up into a grid to simplify navigation. An example position might be 0, 0, N, which means the rover is in the bottom left corner and facing North.

In order to control a rover, NASA sends a simple string of letters. The possible letters are 'L ', 'R ' and 'M '. 'L ' and 'R ' makes the rover spin 90 degrees left or right respectively, without moving from its current spot.

'M ' means move forward one grid point, and maintain the same heading.

Assume that the square directly North from (x, y) is (x, y+1).

INPUT:

The first line of input is the upper-right coordinates of the plateau, the lower-left coordinates are assumed to be 0,0.

The rest of the input is information pertaining to the rovers that have been deployed. Each rover has two lines of input. The first line gives the rover 's position, and the second line is a series of instructions telling the rover how to explore the plateau.

The position is made up of two integers and a letter separated by spaces, corresponding to the x and y co-ordinates and the rover 's orientation.

Each rover will be finished sequentially, which means that the second rover won 't start to move until the first one has finished moving.

OUTPUT

The output for each rover should be its final co-ordinates and heading.

INPUT AND OUTPUT

Test Input:

5 5

1 2 N

LMLMLMLMM

3 3 E

MMRMMRMRRM

火星探测器

一小队机器人探测器将由NASA送上火星高原,探测器将在这个奇特的矩形高原上行驶。

用它们携带的照相机将周围的全景地势图发回到地球。每个探测器的方向和位置将由一个x,y系坐标图和一个表示地理方向的字母表示出来。为了方便导航,平原将被划分为网格状。位置坐标示例:0,0,N,表示探测器在坐标图的左下角,且面朝北方。为控制探测器,NASA会传送一串简单的字母。可能传送的字母为: 'L ', 'R '和 'M '。 'L ',和 'R '分别表示使探测器向左、向右旋转90度,但不离开他所在地点。 'M ' 表示向前开进一个网格的距离,且保持方向不变。假设以广场(高原)的直北方向为y轴的指向。

输入:首先输入的line是坐标图的右上方,假定左下方顶点的坐标为0,0。剩下的要输入的是被分布好的探测器的信息。每个探测器需要输入wo lines。第一条line 提供探测器的位置,第二条是关于这个探测器怎样进行高原探测的一系列说明。位置是由两个整数和一个区分方向的字母组成,对应了探测器的(x,y)坐标和方向。每个探测器的移动将按序完成,即后一个探测器不能在前一个探测器完成移动之前开始移动。

输出:每个探测器的输出应该为它行进到的最终位置坐标和方向。输入和输出 测试如下:

期待的输入:

5 5

1 2 N

LMLMLMLMM

3 3 E

MMRMMRMRRM 期待的输出

1 3 N

5 1 E


【分析】

其实这种题目并不难,主要还是考实现者的问题实现方式


这是文件架构。

【实现】

一 : 方向包含东南西北四个状态,于是我们先写一个枚举类型:

Direction.java

package main.com.thoughtworks.homework.state;

public enum Direction {
	NORTH,	//  北
	SOUTH,	//  南
	WEST,	//  西
	EAST  	//  东
}

二:涉及到不同方向状态的切换,如果我们使用if - else实现对不同状态的操作的话,不仅代码难看,而且不容易维护,扩展难,使用状态模式的方法来实现倒是不错。

     2.1 定义一个State的抽象类

package main.com.thoughtworks.homework.state;


public abstract class State {
	int X;
	int Y;
	Direction direction;
	
	public State(int x, int y, Direction direction) {
		super();
		X = x;
		Y = y;
		this.direction = direction;
	}
	public int getX() {
		return X;
	}
	public void setX(int x) {
		X = x;
	}
	public int getY() {
		return Y;
	}
	public void setY(int y) {
		Y = y;
	}
	public Direction getDirection() {
		return direction;
	}
	public void setDirection(Direction direction) {
		this.direction = direction;
	}
	
	public abstract void turnLeft(Switcher s);
	
	public abstract void turnRight(Switcher s);
	
	public abstract void moveStep(Switcher s);
	
	@Override
	public String toString() {
		return "State [X=" + this.X + ", Y=" + this.Y + ", direction=" + this.direction + "]";
	}
	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + X;
		result = prime * result + Y;
		result = prime * result
				+ ((direction == null) ? 0 : direction.hashCode());
		return result;
	}
	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		State other = (State) obj;
		if (this.X != other.X)
			return false;
		if (this.Y != other.Y)
			return false;
		if (this.direction != other.direction)
			return false;
		return true;
	}	
}
需要注意的是State类中含有三个未实现的方法,turnLeft, turnRight, moveStep, 这三个方法将在具体的State子类中实现,并且仅仅作为单一步骤的实现,例如turnLeft仅仅实现向左转弯,但不前进,moveStep仅仅前进一步。

      2.2 定义一个状态切换器Switcher,实现不同状态的转换

package main.com.thoughtworks.homework.state;

public class Switcher {
	State state;
	
	public Switcher(State state)
	{
		this.state = state;
	}
	public void setState(State state)
	{
		this.state = state;
	}
	
	public State getState()
	{
		return this.state;
	}
	
	public void turnLeft()
	{
		this.state.turnLeft(this);
	}
	
	public void turnRight()
	{
		this.state.turnRight(this);
	}
	
	public void moveStraight()
	{
		this.state.moveStep(this);
	}
}
 

      2.3 实现State的不同子类

        EastState.java

package main.com.thoughtworks.homework.state;

public class EastState extends State{

	public EastState(int x, int y, Direction direction) {
		super(x, y, direction);
	}

	@Override
	public void turnLeft(Switcher s) {
		if(s.getState().getDirection() == Direction.EAST)
		{
			s.setState(new NorthState(this.X, this.Y, Direction.NORTH));
		}
		else
		{
			s.setState(new SouthState(this.X, this.Y, this.direction));
			s.turnLeft();
		}
	}

	@Override
	public void turnRight(Switcher s) {
		if(s.getState().getDirection() == Direction.EAST)
		{
			s.setState(new NorthState(this.X, this.Y, Direction.SOUTH));
		}
		else
		{
			s.setState(new SouthState(this.X, this.Y, this.direction));
			s.turnRight();
		}
	}

	@Override
	public void moveStep(Switcher s) {
		if(s.getState().getDirection() == Direction.EAST)
		{
			this.X += 1;
			s.setState(this);
		}
		else
		{
			s.setState(new SouthState(this.X, this.Y, this.direction));
			s.moveStraight();
		}
	}

}
       

      SouthState.java

package main.com.thoughtworks.homework.state;

public class SouthState extends State{

	public SouthState(int x, int y, Direction direction) {
		super(x, y, direction);
	}

	@Override
	public void turnLeft(Switcher s) {
		if(s.getState().getDirection() == Direction.SOUTH)
		{
			s.setState(new EastState(this.X, this.Y, Direction.EAST));
		}
		else
		{
			s.setState(new WestState(X, Y, direction));
			s.turnLeft();
		}
	}

	@Override
	public void turnRight(Switcher s) {
		if(s.getState().getDirection() == Direction.SOUTH)
		{
			s.setState(new WestState(this.X, this.Y, Direction.WEST));
		}
		else
		{
			s.setState(new WestState(X, Y, direction));
			s.turnRight();
		}
	}

	@Override
	public void moveStep(Switcher s) {
		if(s.getState().getDirection() == Direction.SOUTH)
		{
			this.Y -= 1;
			s.setState(this);
		}
		else
		{
			s.setState(new WestState(X, Y, direction));
			s.moveStraight();
		}
	}
}
   另外的WestState和NorthState实现均类似。

三,  执行器的实现

     执行器就是要执行命令的对象,我们定义为Executer

    Executer.java

package main.com.thoughtworks.homework.executer;

import main.com.thoughtworks.homework.state.Switcher;

public class Executer {
	protected Switcher switcher;
	
	public Executer(Switcher switcher) {
		super();
		this.switcher = switcher;
	}

	public Switcher getSwitcher() {
		return switcher;
	}

	public void setSwitcher(Switcher switcher) {
		this.switcher = switcher;
	}

	public void turnLeft()
	{
		this.switcher.turnLeft();
		this.switcher.moveStraight();
	}
	
	public void turnRight()
	{
		this.switcher.turnRight();
		this.switcher.moveStraight();
	}
	
	public void moveStraight()
	{
		this.switcher.moveStraight();
	}
}
 

      Executer包含了一个状态切换器,用来执行命令时,可以改变状态

 

四、  定义一个命令接口IExecutable,包含一个必须实现的execute方法

     IExecutable.java


package main.com.thoughtworks.homework.executer;

public interface IExecutable {
	void execute(Executer e);
}

   编写向左、向右、前进这几个命令,实现这个接口

package main.com.thoughtworks.homework.executer;


public class LeftCommand implements IExecutable{

	@Override
	public void execute(Executer e) {
		e.turnLeft();
	}

}

package main.com.thoughtworks.homework.executer;


public class RightCommand implements IExecutable{

	@Override
	public void execute(Executer e) {
		e.turnRight();
	}
	
}

package main.com.thoughtworks.homework.executer;


public class StraightCommand implements IExecutable{
	@Override
	public void execute(Executer e) {
		e.moveStraight();
	}

}

五.  主函数调用

package main.com.thoughtworks.homework.main;

import main.com.thoughtworks.homework.executer.*;
import main.com.thoughtworks.homework.state.*;

public class Main {
	public static void main(String[] args)
	{
		Switcher s = new Switcher(new NorthState(2, 4, Direction.SOUTH));
		Executer rover = new Executer(s);
		new LeftCommand().execute(rover);
		
		System.out.println(rover.getSwitcher().getState().toString());
	}
}	

六、可以用静态工厂模式实现初始的时候,对状态State进行实例化工作,在此不贴代码了。另外最后的输出也还没写进来,相信你们都会的!


七、如果这时候我们想扩展一个命令,叫D,执行器接收到这个命令时,会先左转前进一个单元,然后右转前进一个单元,那么我们可以定义一个ExecuterX继承自Executer,添加一个方法

package main.com.thoughtworks.homework.extension;

import main.com.thoughtworks.homework.executer.Executer;
import main.com.thoughtworks.homework.state.Switcher;

public class ExecuterX extends Executer{

	public ExecuterX(Switcher switcher) {
		super(switcher);
		
	}

	public void exMethod()
	{
		this.switcher.turnLeft();
		this.switcher.moveStraight();
                this.switcher.turnRight();
		this.switcher.moveStraight();
	}
}

再定义一个D命令,实现IExecutable接口
package main.com.thoughtworks.homework.extension;

import main.com.thoughtworks.homework.executer.Executer;
import main.com.thoughtworks.homework.executer.IExecutable;

public class DCommand implements IExecutable{

	@Override
	public void execute(Executer e) {
		if(e instanceof ExecuterX)
		{
			ExecuterX ex = (ExecuterX)e;
			ex.exMethod();
		}
	}

}

  
如果各位看官有什么意见或想法,欢迎留言,或者发送邮件到 anrial#126.com。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值