上一篇中,我们介绍了如何实现最基本的,动作中不会引起状态改变的状态模式代码设计,这一篇中,我们介绍如果动作引起了状态发生了连续性改变,该怎么设计。所谓连续性,是指状态改变,但与当前状态也有关系。
这一篇中,我们假设人有向左转的这一个动作,执行这个动作后,人的状态会发生变化。
抽象类State状态:
package com.anvien.practice.state_inner;
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(Person 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;
}
}
具体状态EastState:
package com.anvien.practice.state_inner;
public class EastState extends State{
public EastState(int x, int y, Direction direction) {
super(x, y, direction);
}
@Override
public void turnLeft(Person 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();
}
}
}
具体状态SouthState:
package com.anvien.practice.state_inner;
public class SouthState extends State{
public SouthState(int x, int y, Direction direction) {
super(x, y, direction);
}
@Override
public void turnLeft(Person 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();
}
}
}
其他类似。
具体负责左转的人Person
package com.anvien.practice.state_inner;
public class Person {
State state;
public Person(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);
}
}
测试方法:
package com.anvien.practice.state_inner;
public class Main {
public static void main(String[] args)
{
State state = new SouthState(1,1,Direction.SOUTH);
Person p = new Person(state);
p.turnLeft();
System.out.println(p.getState().toString());
}
}
输出:
State [X=1, Y=1, direction=EAST]