设计模式之状态模式
状态模式
-
状态模式结构图:
-
示例代码:
// 抽象状态类 public abstract class Status { protected ApplicationContext context; public void setContext(ApplicationContext context) { this.context = context; } abstract void handle(); } // 具体状态类A public class ConcreteStatusA extends Status{ @Override public void handle() { System.out.println("状态A执行当前处理"); } } // 具体状态类B public class ConcreteStatusB extends Status{ @Override public void handle() { System.out.println("状态B执行当前处理"); context.setStatus(ApplicationContext.STATUS_A); context.getStatus().handle(); } } // 容器类 @Data public class ApplicationContext { public static final Status STATUS_A = new ConcreteStatusA(); public static final Status STATUS_B = new ConcreteStatusB(); private Status status; { STATUS_A.setContext(this); STATUS_B.setContext(this); } public Status getStatus() { return status; } public void setStatus(Status status) { this.status = status; this.status.setContext(this); } public void handle(){ this.status.handle(); } } // 测试 public class StatusTest { public static void main(String[] args) { ApplicationContext context = new ApplicationContext(); context.setStatus(ApplicationContext.STATUS_A); context.handle(); System.out.println("==================="); context.setStatus(ApplicationContext.STATUS_B); context.handle(); } }
-
总结:
优点:将状态独立为类,提高了系统的可维护性;状态类职责明确且具备扩展性;
缺点:如果一个事物具备很多的状态,则会造成状态类太多,状态类的结构和实现都较为复杂,且对开闭原则支持并不好.