{"id":2968,"date":"2024-01-12T14:00:06","date_gmt":"2024-01-12T14:00:06","guid":{"rendered":"https:\/\/msgprogramator.sk\/?p=2968"},"modified":"2025-07-07T10:57:19","modified_gmt":"2025-07-07T10:57:19","slug":"java-command","status":"publish","type":"post","link":"https:\/\/msgprogramator.sk\/en\/java-command\/","title":{"rendered":"Java design pattern Command"},"content":{"rendered":"<p>Today we will look at another <strong>Java design pattern<\/strong> from the category of <strong>behavioural patterns<\/strong> &#8211; <strong>Command<\/strong>. Design patterns in this category deal with the <strong>interaction <\/strong> between objects and their <strong>responsibilities<\/strong>. <\/p>\n<h2>What is the Command design pattern?<\/h2>\n<p>The <strong>Command <\/strong> design pattern is a pattern that wraps requirements or operations, along with the information to perform them, into separate objects. This information most often includes the method name of the corresponding object along with the method parameters. There are always concepts associated with a pattern: <strong><em>client<\/em><\/strong>, <strong><em>command<\/em><\/strong>, <strong><em>receiver<\/em><\/strong>, <strong><em>invoker<\/em><\/strong>. The client decides which order to execute and when. To execute the command, it moves the command object of the invoker object. The invoker does not know anything about a particular object, only its interface. Its job is to execute the command by calling the <em>execute <\/em> method and, if necessary, store the details of the invoked operation. The receiver then executes the job from the command object.       <\/p>\n<h2>What problem does the Command design pattern solve?<\/h2>\n<p>It solves the problem of separating the object that invokes an operation (the invoker) from the object that performs that operation (the receiver), with the main goal being to provide a flexible connection between the objects that trigger requests and those that process them. These objects contain all the information needed to perform a given operation in the background, and in this way it is possible to work with client requests with different parameters as needed. Requests can be queued for processing, logged or even reverse operations can be implemented.  <\/p>\n<h2>Example of a Command implementation in Java<\/h2>\n<p>The design pattern is a bit more complicated to understand, so I have prepared an example where we will explain the roles of <em>Client<\/em>, <em>Command<\/em>, <em>Receiver<\/em>, <em>Invoker <\/em> in more detail. We are going to write a simple program that controls a torch using commands. <\/p>\n<p><strong><u>Command.java<\/u><\/strong><\/p>\n<pre><code class=\"language-java\" data-line=\"\">package designpatterns;\n\n\/\/ Command rozhranie\npublic interface Prikaz {\n    void vykonat();\n}<\/code><\/pre>\n<p>The <strong>Command <\/strong> interface defines the <em>execute()<\/em> operation that all concrete commands will implement.<\/p>\n<p><strong><u>TurnOnLight.java<\/u><\/strong><\/p>\n<pre><code class=\"language-java\" data-line=\"\">package designpatterns;\n\n\/\/ Konkr\u00e9tny pr\u00edkaz\npublic class ZapnutSvetlo implements Prikaz {\n    private Baterka baterka;\n\n    public ZapnutSvetlo(Baterka baterka) {\n        this.baterka = baterka;\n    }\n\n    @Override\n    public void vykonat() {\n        baterka.zapnut();\n    }\n}<\/code><\/pre>\n<p><strong><u>TurnOffLight.java<\/u><\/strong><\/p>\n<pre><code class=\"language-java\" data-line=\"\">package designpatterns;\n\n\/\/ Konkr\u00e9tny pr\u00edkaz\npublic class VypnutSvetlo implements Prikaz {\n    private Baterka baterka;\n\n    public VypnutSvetlo(Baterka baterka) {\n        this.baterka = baterka;\n    }\n\n    @Override\n    public void vykonat() {\n        baterka.vypnut();\n    }\n}<\/code><\/pre>\n<p>Specifically, the <strong>TurnOnLight<\/strong> and <strong>TurnOffLight<\/strong> commands implement the <strong>Command<\/strong> interface and contain a reference to a specific <strong>Torch<\/strong> object that will perform the corresponding operation.<\/p>\n<p><strong><u>Torch.java<\/u><\/strong><\/p>\n<pre><code class=\"language-java\" data-line=\"\">package designpatterns;\n\n\/\/ Receiver\npublic class Baterka {\n    public void zapnut() {\n        System.out.println(&quot;Baterka svieti&quot;);\n    }\n    public void vypnut() {\n        System.out.println(&quot;Baterka je vypnuta&quot;);\n    }\n}<\/code><\/pre>\n<p>The <strong>Torch<\/strong> class represents a <em>receiver<\/em> and contains the methods that are called when the commands are executed.<\/p>\n<p><strong><u>Switch.java<\/u><\/strong><\/p>\n<pre><code class=\"language-java\" data-line=\"\">package designpatterns;\n\n\/\/ Invoker\npublic class Vypinac {\n    private Prikaz prikaz;\n\n    public void nastavPrikaz(Prikaz prikaz) {\n        this.prikaz = prikaz;\n    }\n\n    public void stlacitTlacidlo() {\n        prikaz.vykonat();\n    }\n}<\/code><\/pre>\n<p>The <strong>Switch <\/strong> class represents an <em>invoker<\/em> and contains a reference to an object of type <strong>Command<\/strong> and has a method <em>pressButton()<\/em> that calls the <em>execute()<\/em> operation of the corresponding command.<\/p>\n<p><strong><u>Main.java<\/u><\/strong><\/p>\n<pre><code class=\"language-java\" data-line=\"\">import designpatterns.*;\n\n\/\/ Klient\npublic class Main {\n    public static void main(String[] args) {\n        \/\/ Receiver\n        Baterka baterka = new Baterka();\n        \/\/ Command(s)\n        Prikaz zapnutSvetlo = new ZapnutSvetlo(baterka);\n        Prikaz vypnutSvetlo = new VypnutSvetlo(baterka);\n        \/\/ Invoker\n        Vypinac vypinac = new Vypinac();\n        \/\/ Nastavenie a spustenie pr\u00edkazu.\n        vypinac.nastavPrikaz(zapnutSvetlo);\n        vypinac.stlacitTlacidlo();\n        \/\/ Nastavenie a spustenie in\u00e9ho pr\u00edkazu.\n        vypinac.nastavPrikaz(vypnutSvetlo);\n        vypinac.stlacitTlacidlo();\n    }\n}<\/code><\/pre>\n<p>The <strong>Main <\/strong> class represents the client. In the <em>Main <\/em> method we create commands to control the torch and link them to the receiver that will process them. We will also create an invoker object &#8211; a switch through which the client sets a specific command that will be executed after the <em>pressButton()<\/em> method is called. In simple terms, the client sends commands to the switch that controls the torch.   <\/p>\n<p>The output from this example is:<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"size-medium wp-image-2428\" src=\"https:\/\/msgprogramator.sk\/wp-content\/uploads\/2024\/01\/vystup-z-prikladu-700-270-300x116.webp\" alt=\"Java design patterns Command \" width=\"300\" height=\"116\" srcset=\"https:\/\/msgprogramator.sk\/wp-content\/uploads\/2024\/01\/vystup-z-prikladu-700-270-300x116.webp 300w, https:\/\/msgprogramator.sk\/wp-content\/uploads\/2024\/01\/vystup-z-prikladu-700-270.webp 700w\" sizes=\"auto, (max-width: 300px) 100vw, 300px\" \/><\/p>\n<h2>Conclusion<\/h2>\n<p>The <strong>Command <\/strong> design pattern is often used when we need to get rid of the dependency of a requirement on a direct concrete implementation. It has a wide range of applications in GUI, network communication, database transactions, etc. <\/p>\n<p>We have prepared the files with the above example in the form of code that you can run directly in Java. <a href=\"https:\/\/msgprogramator.sk\/wp-content\/uploads\/2024\/01\/Command.zip\">Download the Java <strong>Command<\/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 Command design pattern and what is it for? Read our new article and download the sample code.<\/p>\n","protected":false},"author":14,"featured_media":2432,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_acf_changed":false,"footnotes":""},"categories":[57],"tags":[],"class_list":["post-2968","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\/2968","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=2968"}],"version-history":[{"count":5,"href":"https:\/\/msgprogramator.sk\/en\/wp-json\/wp\/v2\/posts\/2968\/revisions"}],"predecessor-version":[{"id":5264,"href":"https:\/\/msgprogramator.sk\/en\/wp-json\/wp\/v2\/posts\/2968\/revisions\/5264"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/msgprogramator.sk\/en\/wp-json\/wp\/v2\/media\/2432"}],"wp:attachment":[{"href":"https:\/\/msgprogramator.sk\/en\/wp-json\/wp\/v2\/media?parent=2968"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/msgprogramator.sk\/en\/wp-json\/wp\/v2\/categories?post=2968"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/msgprogramator.sk\/en\/wp-json\/wp\/v2\/tags?post=2968"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}