注:

转载自 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 Pattern
     
    interface MobileAlertState
    {
        public void alert(AlertStateContext ctx);
    }
     
    class AlertStateContext
    {
        private MobileAlertState currentState;
     
        public AlertStateContext()
        {
            currentState = new Vibration();
        }
     
        public void setState(MobileAlertState state)
        {
            currentState = state;
        }
     
        public void alert()
        {
            currentState.alert(this);
        }
    }
     
    class Vibration implements MobileAlertState
    {
        @Override
        public void alert(AlertStateContext ctx)
        {
             System.out.println("vibration...");
        }
     
    }
     
    class Silent implements MobileAlertState
    {
        @Override
        public void alert(AlertStateContext ctx)
        {
            System.out.println("silent...");
        }
     
    }
     
    class StatePattern
    {
        public static void main(String[] args)
        {
            AlertStateContext stateContext = new AlertStateContext();
            stateContext.alert();
            stateContext.alert();
            stateContext.setState(new Silent());
            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的更多相关文章

  1. State Design Pattern 状态设计模式

    设置好内部状态,然后依据不同的函数作为行为模式,进行状态转换. 有点像Finite Automata算法,两者的思想是一样的. 会Finite Automata,那么这个设计模式就非常easy了. # ...

  2. 说说设计模式~大话目录(Design Pattern)

    回到占占推荐博客索引 设计模式(Design pattern)与其它知识不同,它没有华丽的外表,没有吸引人的工具去实现,它是一种心法,一种内功,如果你希望在软件开发领域有一种新的突破,一个质的飞越,那 ...

  3. 设计模式(Design Pattern)系列之.NET专题

    最近,不是特别忙,重新翻了下设计模式,特地在此记录一下.会不定期更新本系列专题文章. 设计模式(Design pattern)是一套被反复使用.多数人知晓的.经过分类编目的.代码设计经验的总结. 使用 ...

  4. [转]Design Pattern Interview Questions - Part 4

    Bridge Pattern, Composite Pattern, Decorator Pattern, Facade Pattern, COR Pattern, Proxy Pattern, te ...

  5. [转]Design Pattern Interview Questions - Part 2

    Interpeter , Iterator , Mediator , Memento and Observer design patterns. (I) what is Interpreter pat ...

  6. [转]Design Pattern Interview Questions - Part 3

    State, Stratergy, Visitor Adapter and fly weight design pattern from interview perspective. (I) Can ...

  7. [转]Design Pattern Interview Questions - Part 1

    Factory, Abstract factory, prototype pattern (B) What are design patterns? (A) Can you explain facto ...

  8. Design Pattern: Observer Pattern

    1. Brief 一直对Observer Pattern和Pub/Sub Pattern有所混淆,下面打算通过这两篇Blog来梳理这两种模式.若有纰漏请大家指正. 2. Use Case 首先我们来面 ...

  9. Scalaz(10)- Monad:就是一种函数式编程模式-a design pattern

    Monad typeclass不是一种类型,而是一种程序设计模式(design pattern),是泛函编程中最重要的编程概念,因而很多行内人把FP又称为Monadic Programming.这其中 ...

随机推荐

  1. zookeeper从3.4.8升级到3.4.14

    升级背景说明: 最近在做系统安全扫描时,扫出来zookeeper存在安全漏洞 Apache Zookeeper 缓冲区溢出漏洞(CVE--) 官方给出的升级建议: 地址:https://zookeep ...

  2. 【KakaJSON手册】07_Coding_归档_解档

    KakaJSON可以只用一行代码将常用数据进行归档\解档 后面代码中会用到 file 文件路径 // 文件路径(String或者URL都可以) let file = "/Users/mj/D ...

  3. shell中函数的使用

    函数是一个脚本代码块,你可以对它进行自定义命名,并且可以在脚本中任意位置使用这个函数.如果想要这个函数,只要调用这个函数的名称就可以了.使用函数的好处在于模块化以及代码可读性强. (1).函数的创建语 ...

  4. (转载)人脸识别中Softmax-based Loss的演化史

    人脸识别中Softmax-based Loss的演化史  旷视科技 近期,人脸识别研究领域的主要进展之一集中在了 Softmax Loss 的改进之上:在本文中,旷视研究院(上海)(MEGVII Re ...

  5. (三)Java数据结构和算法——冒泡、选择、插入排序算法

    一.冒泡排序 冒泡算法的运作规律如下: ①.比较相邻的元素.如果第一个比第二个大,就交换他们两个. ②.对每一对相邻元素作同样的工作,从开始第一对到结尾的最后一对.这步做完后,最后的元素会是最大的数( ...

  6. lnmp+discuz使用redis缓存(待进一步研究)

    一直说Redis.Redis缓存.一直不清楚怎么用.于是花点时间研究了一下,但是还没搞懂.先把大概内容记录一下,待后续继续学习 1.首先部署lnmp环境,这个我的博客有些,请自行搜索 2.给php添加 ...

  7. idea 打开eclipse 项目 编译出现 Error:(1, 1) java: 非法字符: ‘\ufeff’

    原因分析: Eclipse可以智能的把UTF-8+BOM文件转为普通的UTF-8文件,IDEA没有这个智能转换. 解决: 1 用IDEA转换,先转换为GBK,再转回UTF-8

  8. 【C/C++开发】C++11:右值引用和转发型引用

    右值引用 为了解决移动语义及完美转发问题,C++11标准引入了右值引用(rvalue reference)这一重要的新概念.右值引用采用T&&这一语法形式,比传统的引用T&(如 ...

  9. maven cloudara依赖下载

    最近开发的项目使用到了cloudara的依赖,已经在pom.xml 中配置了cloudara的repository,但是还是无法下载 <repositories> <reposito ...

  10. scala 抽象类

    package com.jason.qianfeng abstract class Person(val gender: String) { val name: String val age: Int ...