网上有很多java设计模式之state状态模式的教程,今天小编为大家提供的是一位java从业者的一些经验。state借口有四个状态类,分别是create、start、end和destroy。
State接口代码
package org.javaer.code.pattern.state;
import java.util.ArrayList;
import java.util.List;
public interface State {
List
public void handle();
}
Create状态类代码
package org.javaer.code.pattern.state;
public class Create implements State {
public Create() {
commands.add(this);
}
@Override
public void handle() {
execute(this);
}
public void execute(State command){
System.out.println(“create”);
commands.get(commands.indexOf(this)+1).handle();
}
}
Start状态类代码
package org.javaer.code.pattern.state;
public class Start implements State{
public Start() {
commands.add(this);
}
@Override
public void handle() {
execute(this);
}
public void execute(State command){
System.out.println(“start”);
commands.get(commands.indexOf(this)+1).handle();
}
}
End状态类代码
package org.javaer.code.pattern.state;
public class End implements State {
public End() {
commands.add(this);
}
@Override
public void handle() {
execute(this);
}
public void execute(State command){
System.out.println(“end”);
commands.get(commands.indexOf(this)+1).handle();
}
}
Destroy状态类代码
package org.javaer.code.pattern.state;
public class Destroy implements State {
public Destroy() {
commands.add(this);
}
@Override
public void handle() {
execute(this);
}
public void execute(State command){
System.out.println(“destory”);
//我这里加了这一句,就是想让它循环的转换状态,就会导致内存溢出
commands.get(commands.indexOf(this)>=commands.size()-1?0:commands.indexOf(this)+1).handle();
}
}
测试类Main代码
package org.javaer.code.pattern.state;
public class Main {
@SuppressWarnings(“unused”)
public static void main(String[] args) {
State state1 = new Create();
State state2 = new Start();
State state3 = new End();
State state4 = new Destroy();
state1.handle();
}
}
输出:
create
start
end
destory
create
start
end
destory
create
start
end
destory
Exception in thread “main” java.lang.StackOverflowError
at sun.nio.cs.UTF_8.updatePositions(Unknown Source)
at sun.nio.cs.UTF_8$Encoder.encodeArrayLoop(Unknown Source)