{"id":3007,"date":"2024-03-01T12:16:51","date_gmt":"2024-03-01T12:16:51","guid":{"rendered":"https:\/\/msgprogramator.sk\/?p=3007"},"modified":"2025-07-07T10:57:27","modified_gmt":"2025-07-07T10:57:27","slug":"java-strategy","status":"publish","type":"post","link":"https:\/\/msgprogramator.sk\/en\/java-strategy\/","title":{"rendered":"Java design pattern Strategy"},"content":{"rendered":"<p>Today we will look at the last <strong>Java<\/strong> <strong>design pattern<\/strong> from the category of <strong>behavioural patterns<\/strong> &#8211; Strategy. Java design patterns in this category deal with the <strong>interaction<\/strong> between objects and their <strong>responsibility<\/strong>.<\/p>\n<h2>What is a Strategy design pattern?<\/h2>\n<p><strong>Strategy <\/strong> is a design pattern that allows you to dynamically change the behaviour of a class or its algorithms as needed at runtime. For example, if we have a class that performs data validation, the structure of the data may not be known before execution, and the validation algorithm to be used is decided just before it is used.   <\/p>\n<h2>What problem does the Strategy design pattern solve?<\/h2>\n<p>The <strong>Strategy <\/strong> pattern addresses the problem of having the flexibility to change the way a certain functionality is implemented in a program at runtime. It allows you to define a family of algorithms or strategies, put each of them in a separate class, and ensure that their objects are interchangeable. <\/p>\n<p>The main goal is to provide the ability to dynamically change the behaviour of the object according to the chosen strategy. A context object is used to switch strategies, which has a reference to the strategy object and can also call its methods.<\/p>\n<h2>Example of a Strategy implementation in Java<\/h2>\n<p>This code demonstrates the use of the <strong>Strategy <\/strong> design pattern in the context of a hockey coach and his ability to switch between offensive and defensive strategies based on the current state of the game.<\/p>\n<p><strong><u>GameStrategy.java<\/u><\/strong><\/p>\n<pre><code class=\"language-java\" data-line=\"\">package designpatterns;\n\npublic interface HernaStrategia {\n    void vykonat();\n}<\/code><\/pre>\n<p><strong>GameStrategy<\/strong> is an interface that defines how to implement a strategy. It contains a single <em>execute()<\/em> method that defines how the strategy is to be executed. <\/p>\n<p><strong><u>OffensiveStrategy.java, DefensiveStrategy.java<\/u><\/strong><\/p>\n<pre><code class=\"language-java\" data-line=\"\">package designpatterns;\n\npublic class UtocnaStrategia implements HernaStrategia {\n    @Override\n    public void vykonat() {\n        System.out.println(&quot;T\u00edm hr\u00e1 v \u00fato\u010dnej form\u00e1cii.&quot;);\n    }\n}\n\npublic class ObrannaStrategia implements HernaStrategia {\n    @Override\n    public void vykonat() {\n        System.out.println(&quot;T\u00edm prech\u00e1dza do obrannej form\u00e1cie.&quot;);\n    }\n}<\/code><\/pre>\n<p><strong>OffensiveStrategy<\/strong> and <strong>DefensiveStrategy<\/strong> are concrete implementations of the <strong>GameStrategy<\/strong> interface. Each of these classes implements the <em>execute()<\/em> method to execute a specific strategy &#8211; offensive or defensive. <\/p>\n<p><strong><u>Coach.java<\/u><\/strong><\/p>\n<pre><code class=\"language-java\" data-line=\"\">package designpatterns;\n\n\/\/ Kontext\npublic class Coach {\n    private HernaStrategia hernaStrategia;\n\n    public void zmenitStrategiu(HernaStrategia novaStrategia) {\n        this.hernaStrategia = novaStrategia;\n    }\n\n    public void vykonatStrategiu() {\n        hernaStrategia.vykonat();\n    }\n}<\/code><\/pre>\n<p>A coach is a context that uses a strategy. It has a GameStrategy attribute that holds the current strategy. The <em>changeStrategy()<\/em> method is used to change the current strategy and the <em>executeStrategy()<\/em> method executes it.<\/p>\n<p><strong><u>Main.java<\/u><\/strong><\/p>\n<pre><code class=\"language-java\" data-line=\"\">import designpatterns.Coach;\nimport designpatterns.HernaStrategia;\nimport designpatterns.ObrannaStrategia;\nimport designpatterns.UtocnaStrategia;\n\npublic class Main {\n    public static void main(String[] args) {\n        Coach coach = new Coach();\n        HernaStrategia utocnaStrategia = new UtocnaStrategia();\n        HernaStrategia obrannaStrategia = new ObrannaStrategia();\n\n        System.out.println(&quot;Za\u010dala sa hra.&quot;);\n\n        \/\/ Coach vyber\u00e1 strat\u00e9giu pod\u013ea priebehu hry\n        \/\/ Za\u010d\u00edname s \u00fato\u010dnou strat\u00e9giou\n        coach.zmenitStrategiu(utocnaStrategia);\n        coach.vykonatStrategiu();\n\n        System.out.println(&quot;T\u00edm striela g\u00f3l a vedie.&quot;);\n\n        \/\/ Ak t\u00edm vyhr\u00e1va, zmen\u00edme na obrann\u00fa strat\u00e9giu\n        \/\/ (simulujeme, \u017ee sa t\u00edm dost\u00e1va do obrannej f\u00e1zy, ke\u010f vedie v z\u00e1pase)\n        coach.zmenitStrategiu(obrannaStrategia);\n        coach.vykonatStrategiu();\n\n        System.out.println(&quot;S\u00faper striela g\u00f3l a vyrovn\u00e1va.&quot;);\n\n        \/\/ Ak t\u00edm prehr\u00e1va, m\u00f4\u017eeme sa op\u00e4\u0165 vr\u00e1ti\u0165 k \u00fato\u010dnej strat\u00e9gii\n        \/\/ (simulujeme, \u017ee t\u00edm znova prech\u00e1dza do \u00fato\u010dnej f\u00e1zy, ke\u010f prehr\u00e1va)\n        coach.zmenitStrategiu(utocnaStrategia);\n        coach.vykonatStrategiu();\n    }\n}<\/code><\/pre>\n<p>The <strong>Main <\/strong> class creates a <strong>Coach <\/strong> instance and two strategy instances &#8211; offensive and defensive. This is followed by a simulation of the match, where the strategies change as the match progresses. <\/p>\n<p>The output of this example is:<\/p>\n<figure id=\"attachment_2839\" aria-describedby=\"caption-attachment-2839\" style=\"width: 450px\" class=\"wp-caption aligncenter\"><img loading=\"lazy\" decoding=\"async\" class=\"size-full wp-image-2838\" src=\"https:\/\/msgprogramator.sk\/wp-content\/uploads\/2024\/03\/vystup-z-prikladu-strategy-450-325.webp\" alt=\"Output from the Java Design Pattern Strategy program.\" width=\"450\" height=\"325\" srcset=\"https:\/\/msgprogramator.sk\/wp-content\/uploads\/2024\/03\/vystup-z-prikladu-strategy-450-325.webp 450w, https:\/\/msgprogramator.sk\/wp-content\/uploads\/2024\/03\/vystup-z-prikladu-strategy-450-325-300x217.webp 300w\" sizes=\"auto, (max-width: 450px) 100vw, 450px\" \/><figcaption id=\"caption-attachment-2839\" class=\"wp-caption-text\">The output of the Strategy design pattern example.<\/figcaption><\/figure>\n<h2>Conclusion<\/h2>\n<p>The <strong>Strategy <\/strong> pattern is often used when we need to dynamically change the behaviour of a class or its strategies on the fly. <\/p>\n<p>We have prepared the files with the above example as code that you can run directly in Java. You can download the <a href=\"https:\/\/msgprogramator.sk\/wp-content\/uploads\/2024\/02\/Strategy.zip\">Java <strong>Strategy<\/strong> code here<\/a>.<\/p>\n<p>If you&#8217;re looking for a job and you&#8217;re a <a href=\"https:\/\/msg-life.sk\/en\/jobs\/java-programmer-senior\/\">Java developer<\/a>, 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 the Java Strategy design pattern and what is it for? Read our new article and download the sample code.<\/p>\n","protected":false},"author":14,"featured_media":2833,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_acf_changed":false,"footnotes":""},"categories":[57],"tags":[],"class_list":["post-3007","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\/3007","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=3007"}],"version-history":[{"count":4,"href":"https:\/\/msgprogramator.sk\/en\/wp-json\/wp\/v2\/posts\/3007\/revisions"}],"predecessor-version":[{"id":5279,"href":"https:\/\/msgprogramator.sk\/en\/wp-json\/wp\/v2\/posts\/3007\/revisions\/5279"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/msgprogramator.sk\/en\/wp-json\/wp\/v2\/media\/2833"}],"wp:attachment":[{"href":"https:\/\/msgprogramator.sk\/en\/wp-json\/wp\/v2\/media?parent=3007"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/msgprogramator.sk\/en\/wp-json\/wp\/v2\/categories?post=3007"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/msgprogramator.sk\/en\/wp-json\/wp\/v2\/tags?post=3007"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}