状态模式:允许通过改变对象内部的状态来改变对象的行为,这个对象的改变就像是改变了这个类一样。
第一步:创建State抽象类 定义一个具体的状态所对应的响应行为的抽象方法。
public abstract class State { public abstract void oper(Operation oper); }
**第二步 **:创建具体的State类 具体的状态类,继承State并实现该状态的行为操作。
public class CtrlC extends State{ //Ctrl C @Override public void oper(Operation oper) { if("Ctrl+c".equals(oper.getOper())){ System.out.println("copy operation"); }else{ oper.setState(new CtrlV()); oper.doOper(); } } } public class CtrlV extends State{ //Ctrl V @Override public void oper(Operation oper) { if("Ctrl+v".equals(oper.getOper())){ System.out.println("paste operation"); }else{ oper.setState(new CtrlX()); oper.doOper(); } } } public class CtrlX extends State{ //Ctrl X @Override public void oper(Operation oper) { if("Ctrl+x".equals(oper.getOper())){ System.out.println("cut operation"); }else{ System.out.println("error"); } } }
第三步:创建Context Context:含有State的一个引用,并负责调用具体状态类的行为操作。
public class Operation { private String oper; private State state; //init concrete State public Operation(){ state = new CtrlC(); } //execute specific operation,then change current State public void doOper(){ state.oper(this); state = new CtrlC(); } public State getState() { return state; } public void setState(State state) { this.state = state; } public String getOper() { return oper; } public void setOper(String oper) { this.oper = oper; } }
第四步:测试
public class MainClass { public static void main(String[] args) { Operation operation = new Operation(); operation.setOper("Ctrl+c"); operation.doOper(); operation.setOper("Ctrl+v"); operation.doOper(); operation.setOper("Ctrl+c"); operation.doOper(); } }