以路飞1234档演示状态模式。
package state;
public interface State {
void attack();
void move();
}
package state;
public class FirstGearState implements State{
@Override
public void attack() {
System.out.println("橡胶手枪");
}
@Override
public void move() {
System.out.println("移速慢");
}
}
package state;
public class SecondGearState implements State{
@Override
public void attack() {
System.out.println("蒸汽手枪");
}
@Override
public void move() {
System.out.println("移速快");
}
}
package state;
public class ThirdGearState implements State{
@Override
public void attack() {
System.out.println("巨象手枪");
}
@Override
public void move() {
System.out.println("移速稍快");
}
}
package state;
public class ForthGearState implements State{
@Override
public void attack() {
System.out.println("大猿王");
}
@Override
public void move() {
System.out.println("能飞");
}
}
package state;
public class LuffyContext {
private State state;
public State getState() {
return state;
}
public void setState(State state) {
this.state = state;
}
public void attack(){
this.state.attack();
}
public void move(){
this.state.move();
}
}
package state;
public class StateTest {
public static void main(String[] args) {
State first=new FirstGearState();
State second=new SecondGearState();
State third=new ThirdGearState();
State forth=new ForthGearState();
LuffyContext luffy=new LuffyContext();
luffy.setState(first);
luffy.attack();
luffy.move();
luffy.setState(second);
luffy.attack();
luffy.move();
luffy.setState(third);
luffy.attack();
luffy.move();
luffy.setState(forth);
luffy.attack();
luffy.move();
}
}
打印结果:
橡胶手枪
移速慢
蒸汽手枪
移速快
巨象手枪
移速稍快
大猿王
能飞
小结:
1.状态模式用于有多个可相互转换的状态,每个状态有不同的实现;
2.不用状态模式也可完成类似功能,只是会用到很多if-else。