網上有很多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();
新聞熱點
疑難解答
圖片精選