{"id":2982,"date":"2024-02-05T12:00:27","date_gmt":"2024-02-05T12:00:27","guid":{"rendered":"https:\/\/msgprogramator.sk\/?p=2982"},"modified":"2025-07-07T10:57:24","modified_gmt":"2025-07-07T10:57:24","slug":"java-memento","status":"publish","type":"post","link":"https:\/\/msgprogramator.sk\/en\/java-memento\/","title":{"rendered":"Java design pattern Memento"},"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; Memento. Design patterns in this category deal with the <strong>interaction<\/strong> between objects and their <strong>responsibility<\/strong>.<\/p>\n<h2>What is the Memento design pattern?<\/h2>\n<p>The <strong>Memento<\/strong> pattern allows the internal state of an object to be preserved without violating the <strong>encapsulation<\/strong> principle, which can be restored if necessary, thus returning the object to its original state.<\/p>\n<h2>What problem does the Memento design pattern solve?<\/h2>\n<p>In applications, it is quite common to save the state that the user has entered as input to the program, e.g. when filling out a web form. If the internet connection is lost, it is useful to be able to restore the last state of the data entered without having to ask the user again.  <\/p>\n<p>In similar situations, where we need to store intermediate states and easily return to them at any time, the Memento design pattern is used, the principle of which is to decouple the storage of the object state from the object itself. The object that needs to store its state creates a Memento object that contains the necessary state information. This Memento object can then be stored (e.g. in history) and used later to restore the object to its original state.  <\/p>\n<p>A well-designed object is encapsulated, i.e. the object&#8217;s data is hidden inside the object and not accessible from outside, so the object itself &#8211; the <strong>Originator <\/strong> &#8211; is responsible for storing the internal state in the (<strong>Memento<\/strong>) object and restoring it from the (<strong>Memento<\/strong>) object. The client (<strong>Caretaker<\/strong>) takes the Memento object from the Originator object when the state is saved and returns it to the Originator object when it is restored. This method allows the internal state of the Originator object to be saved and restored without breaking its encapsulation.  <\/p>\n<h2>Example of a Memento implementation in Java<\/h2>\n<p>We demonstrate how the Memento design pattern can be used to save and restore the state of an object without violating the encapsulation principle by playing a simple game in which the player traverses increasingly dangerous levels, where they may suffer an injury at each step, and where they can save the game state at any time and restore it on demand.<\/p>\n<p><strong><u>Game.java<\/u><\/strong><\/p>\n<pre><code class=\"language-java\" data-line=\"\">package designpatterns;\n\npublic class Hra {\n    private int levelId;\n    private int zdravie;\n\n    public Hra() {\n        spustitHru();\n    }\n\n    public void spustitHru() {\n        this.levelId = 1;\n        this.zdravie = 100;\n        System.out.println(&quot;Sp\u00fa\u0161\u0165am nov\u00fa hru.&quot;);\n        ukazStavHry();\n    }\n\n    public Memento ulozitHru() {\n        System.out.println(&quot;Uklad\u00e1m stav hry.&quot;);\n        return new Memento(levelId, zdravie);\n    }\n\n    public void nacitatHru(Memento memento) {\n        System.out.println(&quot;Na\u010d\u00edtavam ulo\u017een\u00fa poz\u00edciu v hre.&quot;);\n        this.levelId = memento.getLevelId();\n        this.zdravie = memento.getZdravie();\n    }\n\n    public void dokoncitLevel() {\n        levelId++;\n        System.out.println(&quot;Pokra\u010dujem do levelu &quot; + levelId);\n        ukazStavHry();\n    }\n\n    public void zranitSa(int poskodenie) {\n        this.zdravie -= poskodenie;\n        System.out.println(&quot;Hr\u00e1\u010d utrpel zranenie (&quot; + -poskodenie + &quot;)&quot;);\n        ukazStavHry();\n        if (zdravie &lt;= 0) {\n            System.out.println(&quot;Hr\u00e1\u010d stratil cel\u00e9 zdravie. Hra za\u010dne od za\u010diatku.&quot;);\n            spustitHru();\n        }\n    }\n\n    public void ukazStavHry() {\n        System.out.println(&quot;    Level &quot; + levelId + &quot;, Zdravie: &quot; + zdravie);\n    }\n}<\/code><\/pre>\n<p>The <strong>Game <\/strong> class contains methods for starting, saving and loading a game, completing a level, injuring a player and displaying the state of the game.<\/p>\n<p><strong><u>Memento.java<\/u><\/strong><\/p>\n<pre><code class=\"language-java\" data-line=\"\">package designpatterns;\n\npublic class Memento {\n    private int levelId;\n    private int zdravie;\n\n    public Memento(int levelId, int zdravie) {\n        this.levelId = levelId;\n        this.zdravie = zdravie;\n    }\n\n    public int getLevelId() {\n        return levelId;\n    }\n\n    public int getZdravie() {\n        return zdravie;\n    }\n}<\/code><\/pre>\n<p>The <strong>Memento<\/strong> class serves as an object that stores the state of the game. Memento contains information about level (<em>levelId<\/em>) and health (<em>health<\/em>).<\/p>\n<p><strong><u>Playing.java<\/u><\/strong><\/p>\n<pre><code class=\"language-java\" data-line=\"\">import designpatterns.Hra;\nimport designpatterns.Memento;\n\npublic class Hranie {\n    public static void main(String[] args) {\n        Hra hra = new Hra();\n        hra.zranitSa(12);\n        hra.dokoncitLevel();\n        Memento ulozenaPozicia = hra.ulozitHru();\n        hra.zranitSa(24);\n        hra.zranitSa(18);\n        hra.dokoncitLevel();\n        hra.zranitSa(20);\n        hra.zranitSa(12);\n        hra.zranitSa(14);\n        hra.nacitatHru(ulozenaPozicia);\n        hra.ukazStavHry();\n    }\n}<\/code><\/pre>\n<p>The <strong>Playing<\/strong> class contains a <em>main<\/em> method that demonstrates the use of the Memento design pattern. The player starts the game, gets injured, completes the level, saves the game state (Memento), gets injured again, completes another level, gets injured again and, to avoid having to start the game from the beginning, finally resumes the game from the saved position.<\/p>\n<p>The output of this example is:<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"wp-image-2684 size-full\" src=\"https:\/\/msgprogramator.sk\/wp-content\/uploads\/2024\/02\/vystup-z-prikladu-memento-385-550.webp\" alt=\"Example output from the Memento design pattern.\" width=\"385\" height=\"550\" srcset=\"https:\/\/msgprogramator.sk\/wp-content\/uploads\/2024\/02\/vystup-z-prikladu-memento-385-550.webp 385w, https:\/\/msgprogramator.sk\/wp-content\/uploads\/2024\/02\/vystup-z-prikladu-memento-385-550-210x300.webp 210w\" sizes=\"auto, (max-width: 385px) 100vw, 385px\" \/><\/p>\n<h2>Conclusion<\/h2>\n<p>The <strong>Memento<\/strong> pattern is a design pattern that solves the problem of storing and restoring the state of an object so that it can return to a previous state. It is often used to implement an undo\/rollback mechanism or to keep a history of object states.<\/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\/01\/Memento.zip\">Java <strong>Memento <\/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 the Java Memento design pattern and what is it for? Read our new article and download the sample code.<\/p>\n","protected":false},"author":14,"featured_media":2688,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_acf_changed":false,"footnotes":""},"categories":[57],"tags":[],"class_list":["post-2982","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\/2982","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=2982"}],"version-history":[{"count":4,"href":"https:\/\/msgprogramator.sk\/en\/wp-json\/wp\/v2\/posts\/2982\/revisions"}],"predecessor-version":[{"id":5273,"href":"https:\/\/msgprogramator.sk\/en\/wp-json\/wp\/v2\/posts\/2982\/revisions\/5273"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/msgprogramator.sk\/en\/wp-json\/wp\/v2\/media\/2688"}],"wp:attachment":[{"href":"https:\/\/msgprogramator.sk\/en\/wp-json\/wp\/v2\/media?parent=2982"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/msgprogramator.sk\/en\/wp-json\/wp\/v2\/categories?post=2982"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/msgprogramator.sk\/en\/wp-json\/wp\/v2\/tags?post=2982"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}