注:

转载自 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. 使用Flume-Taildir和rocketmq-flume与RocketMQ的结合

    一.Fume-Taidir Flume1.7.0加入了taildirSource作为agent的source.可以说是 Spooling Directory Source + Exec Source ...

  2. flask 运行 flask db init 报错,init-db 命令找不到

    flask init-db 结果是 `Error: No such command “init-db”. 那是因为init-db 已经被 flask db init 给代替了 运行 flask db ...

  3. PL/SQL【32位】连接Oracle 11g【64位】

    下载64位Oracle安装: 下载PL/SQL安装:下载instantclient-basic-win32-12.1.0.1.0.zip,解压后剪切instantclient_12_1文件夹,粘贴到O ...

  4. matlab学习笔记13_3创建函数句柄

    一起来学matlab-matlab学习笔记13函数 13_3 创建函数句柄 觉得有用的话,欢迎一起讨论相互学习~Follow Me 参考文献 https://ww2.mathworks.cn/help ...

  5. 小于K的两数之和

    给你一个整数数组 A 和一个整数 K,请在该数组中找出两个元素,使它们的和小于 K但尽可能地接近 K,返回这两个元素的和. 如不存在这样的两个元素,请返回 -1. 示例1: 输入:A = [34,23 ...

  6. helm安使用

    参照:https://juejin.im/post/5b6590afe51d4519962f02b1

  7. 量化编程技术—pandas与数据分析

    # -*- coding: utf-8 -*- # @Date: 2017-08-26 # @Original: import numpy as np stock_cnt = 200 view_day ...

  8. MacbookPro15 2019 闪屏雪花现象方案汇总

    1. 系统偏好设置,显示器,关闭 "自动调节亮度" "原彩显示",即取消勾选. 2. 系统偏好设置,节能,关闭 "自动切换图形卡模式",即取 ...

  9. Google Adsense(谷歌网站联盟)广告申请指南

    Google AdSense 是一种获取收入的快速简便的方法,适合于各种规模的网站发布商.它可以在网站的内容网页上展示相关性较高的 Google 广告,并且这些广告不会过分夸张醒目.由于所展示的广告同 ...

  10. 关于JavaScript面向对象那些事

    当你在使用手机的时候,你会发现,你并不懂得其中的原理就会操作了,其实这就是面向对象的思想.面向对象还有很多地方都会运用到.JavaScript也不例外,现在跟随我的脚步,来学习一下吧. 面向过程和面向 ...