網(wǎng)上有很多java設(shè)計模式之state狀態(tài)模式的教程,今天小編為大家提供的是一位java從業(yè)者的一些經(jīng)驗。state借口有四個狀態(tài)類,分別是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狀態(tài)類代碼
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狀態(tài)類代碼
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狀態(tài)類代碼
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狀態(tài)類代碼
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”);
//我這里加了這一句,就是想讓它循環(huán)的轉(zhuǎn)換狀態(tài),就會導(dǎo)致內(nèi)存溢出
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();
新聞熱點
疑難解答
圖片精選