注:

转载自 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. [windows bat]如何启动一个新的cmd窗口并在其内执行命令

    两种方式: start cmd /k echo Hello, World! # # 执行完毕以后,新开的窗口不会自动关闭 start cmd /C pause # 执行完毕以后,新开的窗口会自动关闭 ...

  2. oracle plsql 自定义异常

    set serveroutput on DECLARE ; pename emp.ename%type; --自定义异常 no_emp_found exception; begin open cemp ...

  3. Linux的.a、.so和.o文件 对比 window下的dll,lib,exe文件

    连续几天终于将一个又一个问题解决了,这里说其中一个问题 描述问题:使用多线程pthread的时候,(我用的IDE,CODEBOLCKS)编译后发现直接弹出窗口,程序还没有被Build..巴拉巴拉,然后 ...

  4. vs解决方案中添加文件夹

    一般我们在github上面看到的项目结构基本都是把项目放到src文件夹中,test放测试 查了半天也没查到这个是怎么产生的...这边只能用比较笨的方法来完成. 解决方法中是允许我们添加解决方案文件夹, ...

  5. 湖南省第十三届大学生计算机程序设计竞赛 Football Training Camp 贪心

    2007: Football Training Camp[原创-转载请说明] Submit Page   Summary   Time Limit: 1 Sec     Memory Limit: 1 ...

  6. LeetCode 1089. 复写零(Duplicate Zeros) 72

    1089. 复写零 1089. Duplicate Zeros 题目描述 给你一个长度固定的整数数组 arr,请你将该数组中出现的每个零都复写一遍,并将其余的元素向右平移. 注意:请不要在超过该数组长 ...

  7. [转帖]插曲:大白话带你认识Kafka

    插曲:大白话带你认识Kafka 2019-11-18 21:58:27 从事Java 阅读数 2更多 分类专栏: java Kafaka   版权声明:本文为博主原创文章,遵循CC 4.0 BY-SA ...

  8. 池化方法总结(Pooling)

       https://blog.csdn.net/mao_kun/article/details/50507376 在卷积神经网络中,我们经常会碰到池化操作,而池化层往往在卷积层后面,通过池化来降低卷 ...

  9. 网络爬虫第五章之Scrapy框架

    第一节:Scrapy框架架构 Scrapy框架介绍 写一个爬虫,需要做很多的事情.比如:发送网络请求.数据解析.数据存储.反反爬虫机制(更换ip代理.设置请求头等).异步请求等.这些工作如果每次都要自 ...

  10. count_if 功能模板

    count_if 功能模板 template <class InputIterator, class UnaryPredicate> typename iterator_traits< ...