{"id":3005,"date":"2024-02-23T16:00:26","date_gmt":"2024-02-23T16:00:26","guid":{"rendered":"https:\/\/msgprogramator.sk\/?p=3005"},"modified":"2025-07-07T10:57:27","modified_gmt":"2025-07-07T10:57:27","slug":"java-state","status":"publish","type":"post","link":"https:\/\/msgprogramator.sk\/en\/java-state\/","title":{"rendered":"Java design pattern State"},"content":{"rendered":"<p>Today we will look at another <strong>Java<\/strong> <strong>design pattern<\/strong> from the category of <strong>behavioural patterns<\/strong> &#8211; State. Java design patterns in this category deal with the <strong>interaction<\/strong> between objects and their <strong>responsibility<\/strong>.<\/p>\n<h2>What is the State design pattern?<\/h2>\n<p><strong>State <\/strong> is a design pattern that allows an object to change its behaviour when its internal state changes. In the pattern, we create objects that represent individual states, and a context object whose behaviour changes depending on the state of the object. <\/p>\n<p>For a better understanding, let&#8217;s imagine a simple ticket machine. Its behaviour varies depending on the stage of the purchase process (specific state) it is in (e.g. ticket selection, payment, confirmation). Implementing this automated process using the State design pattern would make the code clearer by breaking the business logic of each phase into separate states.  <\/p>\n<h2>What problem does the State pattern solve?<\/h2>\n<p>The <strong>State <\/strong> pattern solves the problem of an object behaving differently depending on its current state. It allows you to define different states and transitions between them, while keeping the state logic separate from the main object logic. This concept is similar to that of finite state machines (<strong>FSMs<\/strong>). The behaviour of each state is defined independently of the other states, and adding new states should not affect the behaviour of existing states.   <\/p>\n<h2>Example of a State implementation in Java<\/h2>\n<p>The practical use of the <strong>State <\/strong> design pattern is illustrated by the example of traffic lights with red, orange and green states that control road traffic.<\/p>\n<p><strong><u>TrafficLightState.java<\/u><\/strong><\/p>\n<pre><code class=\"language-java\" data-line=\"\">package designpatterns;\n\npublic interface StavSemaforu {\n    void vykonat();\n}<\/code><\/pre>\n<p>The <strong>TrafficLightState<\/strong> is the interface that defines the <em>execute()<\/em> method. Each traffic light state (red, orange, green) implements this interface and provides its own implementation of <em>execute()<\/em>.<\/p>\n<p><strong><u>Red.java, Orange.java, Green.java<\/u><\/strong><\/p>\n<pre><code class=\"language-java\" data-line=\"\">package designpatterns;\n\npublic class Cervena implements StavSemaforu {\n    @Override\n    public void vykonat() {\n        System.out.println(&quot;Svetlo na semafore sa preplo na \u010derven\u00fa - prem\u00e1vka sa zastavila.&quot;);\n    }\n}\n\npublic class Oranzova implements StavSemaforu {\n    @Override\n    public void vykonat() {\n        System.out.println(&quot;Svetlo na semafore sa preplo na oran\u017eov\u00fa - \u010dak\u00e1 sa na zmenu.&quot;);\n    }\n}\n\npublic class Zelena implements StavSemaforu {\n    @Override\n    public void vykonat() {\n        System.out.println(&quot;Svetlo na semafore sa preplo na zelen\u00fa - prem\u00e1vka sa rozbieha.&quot;);\n    }\n}<\/code><\/pre>\n<p><strong>Red<\/strong>, <strong>Orange<\/strong> and <strong>Green<\/strong> are implementations of the <strong>TrafficLightState<\/strong> interface. Each of these classes represents one particular traffic light state and provides its own implementation for <em>execute()<\/em>.<\/p>\n<p><strong><u>TrafficLights.java<\/u><\/strong><\/p>\n<pre><code class=\"language-java\" data-line=\"\">package designpatterns;\n\n\/\/ Kontext, ktory prepina stavy\npublic class Semafor {\n    private StavSemaforu stav;\n\n    public Semafor() {\n        this.stav = new Oranzova();\n    }\n\n    public void prepnut(StavSemaforu novyStav) {\n        this.stav = novyStav;\n    }\n\n    public void vykonat() {\n        stav.vykonat();\n    }\n}<\/code><\/pre>\n<p><strong>Traffic Lights<\/strong> is a class that represents a context where traffic light states change. In this case, the Traffic Lights will be initialized to <strong>orange<\/strong>. It has a <em>switch()<\/em> method that changes the current traffic light state to the specified new state. It also has an <em>execute()<\/em> method that executes the current state of the traffic lights.<\/p>\n<p><strong><u>Main.java<\/u><\/strong><\/p>\n<pre><code class=\"language-java\" data-line=\"\">import designpatterns.Cervena;\nimport designpatterns.Oranzova;\nimport designpatterns.Semafor;\nimport designpatterns.Zelena;\n\npublic class Main {\n    public static void main(String[] args) {\n        \/\/ Semafor je na zaciatku inicializovany na stav oranzova.\n        Semafor semafor = new Semafor();\n        semafor.vykonat();\n        semafor.prepnut(new Cervena());\n        semafor.vykonat();\n        semafor.prepnut(new Oranzova());\n        semafor.vykonat();\n        semafor.prepnut(new Zelena());\n        semafor.vykonat();\n    }\n}<\/code><\/pre>\n<p>In the <strong>Main <\/strong> class we simulate the operation of traffic lights. We create an instance of the traffic lights, initially in the orange state. We then change the state of the lights using the <em>switch()<\/em> method and then call the <em>execute()<\/em> method, which handles the business logic defined for that state.  <\/p>\n<p>The output of this example is:<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"wp-image-2780 size-full\" src=\"https:\/\/msgprogramator.sk\/wp-content\/uploads\/2024\/02\/vystup-z-prikladu-state-830-240.webp\" alt=\"Sample output for Java design pattern State \" width=\"830\" height=\"240\" srcset=\"https:\/\/msgprogramator.sk\/wp-content\/uploads\/2024\/02\/vystup-z-prikladu-state-830-240.webp 830w, https:\/\/msgprogramator.sk\/wp-content\/uploads\/2024\/02\/vystup-z-prikladu-state-830-240-300x87.webp 300w, https:\/\/msgprogramator.sk\/wp-content\/uploads\/2024\/02\/vystup-z-prikladu-state-830-240-768x222.webp 768w\" sizes=\"auto, (max-width: 830px) 100vw, 830px\" \/><\/p>\n<h2>Conclusion<\/h2>\n<p>The <strong>State <\/strong> pattern is useful when we have defined a finite number of states for an object to pass through, and we need to perform some action when its internal state changes.<\/p>\n<p>We have prepared the files with the above example in the form of code that you can run directly in Java. You can download the <a href=\"https:\/\/msgprogramator.sk\/wp-content\/uploads\/2024\/02\/State.zip\">Java <strong>State<\/strong> code here.<\/a><\/p>\n<p>If you&#8217;re a <a href=\"https:\/\/msg-life.sk\/en\/jobs\/java-programmer-senior\/\">Java developer<\/a> looking for work, check out our <a href=\"https:\/\/msg-life.sk\/en\/benefits\/\">employee benefits<\/a> and respond to our <a href=\"https:\/\/msg-life.sk\/en\/jobs\/\">job offers<\/a>!<\/p>\n","protected":false},"excerpt":{"rendered":"<p>What is Java State design pattern and what is it for? Read our new article and download the sample code.<\/p>\n","protected":false},"author":14,"featured_media":2775,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_acf_changed":false,"footnotes":""},"categories":[57],"tags":[],"class_list":["post-3005","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-java"],"acf":[],"aioseo_notices":[],"_links":{"self":[{"href":"https:\/\/msgprogramator.sk\/en\/wp-json\/wp\/v2\/posts\/3005","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/msgprogramator.sk\/en\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/msgprogramator.sk\/en\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/msgprogramator.sk\/en\/wp-json\/wp\/v2\/users\/14"}],"replies":[{"embeddable":true,"href":"https:\/\/msgprogramator.sk\/en\/wp-json\/wp\/v2\/comments?post=3005"}],"version-history":[{"count":3,"href":"https:\/\/msgprogramator.sk\/en\/wp-json\/wp\/v2\/posts\/3005\/revisions"}],"predecessor-version":[{"id":5277,"href":"https:\/\/msgprogramator.sk\/en\/wp-json\/wp\/v2\/posts\/3005\/revisions\/5277"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/msgprogramator.sk\/en\/wp-json\/wp\/v2\/media\/2775"}],"wp:attachment":[{"href":"https:\/\/msgprogramator.sk\/en\/wp-json\/wp\/v2\/media?parent=3005"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/msgprogramator.sk\/en\/wp-json\/wp\/v2\/categories?post=3005"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/msgprogramator.sk\/en\/wp-json\/wp\/v2\/tags?post=3005"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}