java 设计模式之State(状态模式)
java 设计模式之State(状态模式)
在状态模式中,一个类的行为基于它的状态的改变而改变。状态模式归属于行为型模式。
在下面的实例中,我们创建了一个接口State,定义了一个操作方法,两个实现类StartState和StopState。另外,创建了一个上下文类Context,这个类关联到State类。UML类图如下所示:
//状态类 public interface State { public void doAction(Context context); } //实现类StartState.java public class StartState implements State { public void doAction(Context context) { System.out.println("Player is in start state"); context.setState(this); } public String toString(){ return "Start State"; } } //实现StopState.java public class StopState implements State { public void doAction(Context context) { System.out.println("Player is in stop state"); context.setState(this); } public String toString(){ return "Stop State"; } } //上下文Context.java 实际运用时可自行更改 public class Context { private State state; public Context(){ state = null; } public void setState(State state){ this.state = state; } public State getState(){ return state; } } //测试类 public class StatePatternDemo { public static void main(String[] args) { Context context = new Context(); StartState startState = new StartState(); startState.doAction(context); System.out.println(context.getState().toString()); StopState stopState = new StopState(); stopState.doAction(context); System.out.println(context.getState().toString()); } }
输出结果
Player is in start state Start State Player is in stop state Stop State
如有疑问请留言或者到本站社区交流讨论,感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!
相关文章
springboot使用AOP+反射实现Excel数据的读取
本文主要介绍了springboot使用AOP+反射实现Excel数据的读取,文中通过示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下2022-01-01Spring Data JPA中的Specification动态查询详解
Specification是一个设计模式,用于企业级应用开发中,其主要目的是将业务规则从业务逻辑中分离出来,在数据查询方面,Specification可以定义复杂的查询,使其更易于重用和测试,这篇文章主要介绍了Spring Data JPA中的Specification动态查询详解,需要的朋友可以参考下2023-07-07Springboot详解整合SpringSecurity实现全过程
Spring Security基于Spring开发,项目中如果使用Springboot作为基础,配合Spring Security做权限更加方便,而Shiro需要和Spring进行整合开发。因此作为spring全家桶中的Spring Security在java领域很常用2022-07-07Idea进行pull的时候Your local changes would be
这篇文章主要介绍了Idea进行pull的时候Your local changes would be overwritten by merge.具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教2023-11-11SpringBoot结合ElasticSearch实现模糊查询的项目实践
本文主要介绍了SpringBoot结合ElasticSearch实现模糊查询的项目实践,主要实现模糊查询、批量CRUD、排序、分页和高亮功能,具有一定的参考价值,感兴趣的可以了解一下2024-03-03SpringSecurity+OAuth2.0 搭建认证中心和资源服务中心流程分析
OAuth 2.0 主要用于在互联网上安全地委托授权,广泛应用于身份验证和授权场景,这篇文章介绍SpringSecurity+OAuth2.0 搭建认证中心和资源服务中心,感兴趣的朋友一起看看吧2024-01-01
最新评论