State Design Pattern
注:
转载自 https://www.geeksforgeeks.org/state-design-pattern/ 【以便查阅,非原创】
State Design Pattern
State pattern is one of the behavioral design pattern. State design pattern is used when an Object changes its behavior based on its internal state.
If we have to change behavior of an object based on its state, we can have a state variable in the Object and use if-else condition block to perform different actions based on the state. State pattern is used to provide a systematic and lose-coupled way to achieve this through Context and State implementations.
UML Diagram of State Design Pattern

- Context: Defines an interface to client to interact. It maintains references to concrete state object which may be used to define current state of object.
- State: Defines interface for declaring what each concrete state should do.
- ConcreteState: Provides implementation for methods defined in State.
Example of State Design Pattern
In below example, we have implemented a mobile state scenario . With respect to alerts, a mobile can be in different states. For example, vibration and silent. Based on this alert state, behavior of the mobile changes when an alert is to be done.// Java program to demonstrate working of// State Design PatterninterfaceMobileAlertState{publicvoidalert(AlertStateContext ctx);}classAlertStateContext{privateMobileAlertState currentState;publicAlertStateContext(){currentState =newVibration();}publicvoidsetState(MobileAlertState state){currentState = state;}publicvoidalert(){currentState.alert(this);}}classVibrationimplementsMobileAlertState{@Overridepublicvoidalert(AlertStateContext ctx){System.out.println("vibration...");}}classSilentimplementsMobileAlertState{@Overridepublicvoidalert(AlertStateContext ctx){System.out.println("silent...");}}classStatePattern{publicstaticvoidmain(String[] args){AlertStateContext stateContext =newAlertStateContext();stateContext.alert();stateContext.alert();stateContext.setState(newSilent());stateContext.alert();stateContext.alert();stateContext.alert();}}Output:
vibration...
vibration...
silent...
silent...
silent...Advantages of State Design Pattern
- With State pattern, the benefits of implementing polymorphic behavior are evident, and it is also easier to add states to support additional behavior.
- In the State design pattern, an object’s behavior is the result of the function of its state, and the behavior gets changed at runtime depending on the state. This removes the dependency on the if/else or switch/case conditional logic. For example, in the TV remote scenario, we could have also implemented the behavior by simply writing one class and method that will ask for a parameter and perform an action (switch the TV on/off) with an if/else block.
- The State design pattern also improves Cohesion since state-specific behaviors are aggregated into the ConcreteState classes, which are placed in one location in the code.
Disadvantages of State Design Pattern
- The State design pattern can be used when we need to change state of object at runtime by inputting in it different subclasses of some State base class. This circumstance is advantage and disadvantage in the same time, because we have a clear separate State classes with some logic and from the other hand the number of classes grows up.
State Design Pattern的更多相关文章
- State Design Pattern 状态设计模式
设置好内部状态,然后依据不同的函数作为行为模式,进行状态转换. 有点像Finite Automata算法,两者的思想是一样的. 会Finite Automata,那么这个设计模式就非常easy了. # ...
- 说说设计模式~大话目录(Design Pattern)
回到占占推荐博客索引 设计模式(Design pattern)与其它知识不同,它没有华丽的外表,没有吸引人的工具去实现,它是一种心法,一种内功,如果你希望在软件开发领域有一种新的突破,一个质的飞越,那 ...
- 设计模式(Design Pattern)系列之.NET专题
最近,不是特别忙,重新翻了下设计模式,特地在此记录一下.会不定期更新本系列专题文章. 设计模式(Design pattern)是一套被反复使用.多数人知晓的.经过分类编目的.代码设计经验的总结. 使用 ...
- [转]Design Pattern Interview Questions - Part 4
Bridge Pattern, Composite Pattern, Decorator Pattern, Facade Pattern, COR Pattern, Proxy Pattern, te ...
- [转]Design Pattern Interview Questions - Part 2
Interpeter , Iterator , Mediator , Memento and Observer design patterns. (I) what is Interpreter pat ...
- [转]Design Pattern Interview Questions - Part 3
State, Stratergy, Visitor Adapter and fly weight design pattern from interview perspective. (I) Can ...
- [转]Design Pattern Interview Questions - Part 1
Factory, Abstract factory, prototype pattern (B) What are design patterns? (A) Can you explain facto ...
- Design Pattern: Observer Pattern
1. Brief 一直对Observer Pattern和Pub/Sub Pattern有所混淆,下面打算通过这两篇Blog来梳理这两种模式.若有纰漏请大家指正. 2. Use Case 首先我们来面 ...
- Scalaz(10)- Monad:就是一种函数式编程模式-a design pattern
Monad typeclass不是一种类型,而是一种程序设计模式(design pattern),是泛函编程中最重要的编程概念,因而很多行内人把FP又称为Monadic Programming.这其中 ...
随机推荐
- Flutter Plugin开发简单示例
新建Plugin项目: flutter create --template=plugin -i swift -a javahello lib/hello.dart: 插件包的Dart API. and ...
- Kafka高级设计和架构,一文深化理解
主题: 1.kafka是写磁盘还是写内存? 2.kafka究竟是由 consumer 从 broker 那里拉数据,还是由 broker 将数据推到 consumer? 3.如何区分已消费(consu ...
- Linux CentOS7 通过 yum 搭建 svn 服务器,并配置权限
1,使用 yum 安装 svn 服务器 yum -y install subversion rpm -ql subversion -- 改命令可以查看 svn 的安装位置 2,创建仓库根目录,可任意选 ...
- RTSP Spectification
Refer: https://www.ietf.org/rfc/rfc2326.txt Network Working Group H. SchulzrinneRequest for Comments ...
- [源码]Python调用C# DLL例子(Python与.Net交互)
K8Cscan C# DLL例子代码 namespace CscanDLL { public class scan { public static string run(string ip) { if ...
- 【LOJ511】[LibreOJ NOI Round #1]验题(动态DP)
我这道题写了整!整!三!天! 我要一定要写这篇博客来表达我复!杂!的!心!情! 题目 LOJ511 官方题解(这个题解似乎不是很详细,我膜 std 才看懂的) 调这道题验证了我校某人的一句话:调题是一 ...
- Java生产消费者模型——代码解析
我们将生产者.消费者.库存.和调用线程的主函数分别写进四个类中,通过抢夺非线程安全的数据集合来直观的表达在进行生产消费者模型的过程中可能出现的问题与解决办法. 我们假设有一个生产者,两个消费者来共同抢 ...
- day07——数据类型补充、坑、二次编码
day07 数据类型补充 str 首字母大写:capitalize() name = 'alex' name1 = name.capitalize() print(name1) 每个单词首字母大写:t ...
- TCP/IP详解 IP路由选择
TCP/IP详解 IP路由选择 在本篇文章当中, 将通过例子来说明IP路由选择器过程 如图所示, 主机A与主机B分别是处在两个不同的子网当中, 中间通过一个路由连接. 如果主机A请求与主机B进行通行, ...
- [loj 6253] Yazid的新生舞会
(很久之前刷的题现在看起来十分陌生a) 题意: 给你一个长度为n的序列A,定义一个区间$[l,r]$是“新生舞会的”当且仅当该区间的众数次数严格大于$\frac{r-l+1}{2}$,求有多少子区间是 ...