{"id":2373,"date":"2023-12-22T10:10:10","date_gmt":"2023-12-22T10:10:10","guid":{"rendered":"https:\/\/msgprogramator.sk\/?p=2373"},"modified":"2025-07-07T10:57:22","modified_gmt":"2025-07-07T10:57:22","slug":"java-flyweight","status":"publish","type":"post","link":"https:\/\/msgprogramator.sk\/en\/java-flyweight\/","title":{"rendered":"Java design pattern Flyweight"},"content":{"rendered":"<p>Today we will take a look at another <strong>Java <\/strong><strong>design pattern<\/strong> from the <strong>structural patterns<\/strong> category &#8211; Flyweight. Design patterns in this category deal with class structure such as <strong>inheritance<\/strong> and <strong>composition<\/strong>.<\/p>\n<h2>What is the Flyweight design pattern?<\/h2>\n<p><strong>Flyweight<\/strong> is a design pattern that is primarily used to reduce the number of objects created because it attempts to reuse existing objects with the same or similar properties at the class level, and only creates a new object when no matching object is found. This minimizes the amount of memory used for data shared between similar objects.<\/p>\n<h2>What problem does the Flyweight design pattern solve?<\/h2>\n<p>Flyweight solves the problem in applications that work with a large number of objects, which would take a lot of memory if stored separately, and the cost of creating them is not negligible. This pattern solves the problem by extracting common data and sharing it between objects, reducing the amount of memory required and making use of already created objects.<\/p>\n<h2>Example of Flyweight implementation in Java<\/h2>\n<p>We will now write a program to simulate a simple system for running a pizza restaurant, and use it to demonstrate the use of the <strong>Flyweight <\/strong> design pattern to efficiently share instances of pizza and minimize the number of objects created. The program creates a pizzeria, takes orders for different types of pizzas and serves them. It will consist of <em>Pizza<\/em>, <em>Order<\/em>, <em>Pizzeria<\/em> and <em>Main<\/em> classes.<\/p>\n<p><strong><u>Pizza.java<\/u><\/strong><\/p>\n<pre><code class=\"language-java\" data-line=\"\">package designpatterns;\n\nimport java.util.HashMap;\nimport java.util.Map;\n\npublic class Pizza {\n    private static Map&lt;String, Pizza&gt; pizzaCache = new HashMap&lt;&gt;();\n    private String nazov;\n\n    private Pizza(String nazov) {\n        this.nazov = nazov;\n    }\n\n    public static Pizza intern(String nazov) {\n        pizzaCache.putIfAbsent(nazov, new Pizza(nazov));\n        return pizzaCache.get(nazov);\n    }\n\n    public static int pocetDruhov() {\n        return pizzaCache.size();\n    }\n\n    @Override\n    public String toString() {\n        return nazov;\n    }\n}<\/code><\/pre>\n<p>The <strong>Pizza<\/strong> class represents a type of pizza and uses the Flyweight pattern to share instances of pizzas with the same name. It has an <em>intern()<\/em> method that creates a new pizza only if it doesn&#8217;t already exist, and a <em>pocetDruhov()<\/em> method that returns the number of different kinds of pizzas.<\/p>\n<p><strong><u>Objednavka.java<\/u><\/strong><\/p>\n<pre><code class=\"language-java\" data-line=\"\">package designpatterns;\n\npublic class Objednavka {\n    private Pizza pizza;\n    private int cisloStolu;\n\n    private Objednavka(Pizza pizza, int cisloStolu) {\n        this.pizza = pizza;\n        this.cisloStolu = cisloStolu;\n    }\n\n    public static Objednavka create(String nazov, int cisloStolu) {\n        Pizza pizza = Pizza.intern(nazov);\n        return new Objednavka(pizza, cisloStolu);\n    }\n\n    @Override\n    public String toString() {\n        return &quot;Posielam pizzu &quot; + pizza + &quot; na stol &quot; + cisloStolu;\n    }\n}<\/code><\/pre>\n<p>The <strong>Objednavka<\/strong> class represents a pizza order. Each order contains a link to a specific pizza and the table number where the pizza is to be delivered.<\/p>\n<p><strong><u>Pizzeria.java<\/u><\/strong><\/p>\n<pre><code class=\"language-java\" data-line=\"\">package designpatterns;\n\npublic class Pizzeria {\n    private java.util.List&lt;Objednavka&gt; objednavky = new java.util.ArrayList&lt;&gt;();\n\n    public void prijatObjednavku(String druh, int cisloStolu) {\n        objednavky.add(Objednavka.create(druh, cisloStolu));\n    }\n\n    public void obsluzit() {\n        for (Objednavka order : objednavky) {\n            System.out.println(order);\n        }\n    }\n\n    public int pocetPrijatychObjednavok() {\n        return objednavky.size();\n    }\n}<\/code><\/pre>\n<p>The <strong>Pizzeria<\/strong> class represents a pizzeria that accepts orders and provides methods for processing and listing orders. It also provides a method for obtaining the number of orders received.<\/p>\n<p><strong><u>Main.java<\/u><\/strong><\/p>\n<pre><code class=\"language-java\" data-line=\"\">import designpatterns.Pizzeria;\nimport designpatterns.Pizza;\n\npublic class Main {\n    public static void main(String[] args) {\n        Pizzeria pizzeria = new Pizzeria();\n        pizzeria.prijatObjednavku(&quot;Hawai&quot;, 2);\n        pizzeria.prijatObjednavku(&quot;Quattro Formaggi&quot;, 1);\n        pizzeria.prijatObjednavku(&quot;Margherita&quot;, 1);\n        pizzeria.prijatObjednavku(&quot;Napoletana&quot;, 5);\n        pizzeria.prijatObjednavku(&quot;Hawai&quot;, 4);\n        pizzeria.prijatObjednavku(&quot;Quattro Formaggi&quot;, 3);\n        pizzeria.prijatObjednavku(&quot;Margherita&quot;, 3);\n        pizzeria.prijatObjednavku(&quot;Hawai&quot;, 3);\n        pizzeria.prijatObjednavku(&quot;Margherita&quot;, 6);\n        pizzeria.prijatObjednavku(&quot;Quattro Formaggi&quot;, 2);\n        pizzeria.obsluzit();\n        System.out.println();\n        System.out.println(&quot;Pocet prijatych objednavok: &quot; + pizzeria.pocetPrijatychObjednavok());\n        System.out.println(&quot;Pocet pouzitych objektov typu pizza: &quot; + Pizza.pocetDruhov());\n    }\n}<\/code><\/pre>\n<p>In the <em>main<\/em> method, a pizzeria instance is created and then various pizza orders are created. All orders are served and finally the number of orders received and the number of <strong>Pizza<\/strong> objects used are listed. Thus, we have demonstrated the sharing of Pizza-type objects between different orders.<\/p>\n<p>The output of this example is:<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-2251\" src=\"https:\/\/msgprogramator.sk\/wp-content\/uploads\/2023\/12\/vystup-z-prikladu-950-730.webp\" alt=\"Screenshot of the output from the example\" width=\"950\" height=\"730\" srcset=\"https:\/\/msgprogramator.sk\/wp-content\/uploads\/2023\/12\/vystup-z-prikladu-950-730.webp 950w, https:\/\/msgprogramator.sk\/wp-content\/uploads\/2023\/12\/vystup-z-prikladu-950-730-300x231.webp 300w, https:\/\/msgprogramator.sk\/wp-content\/uploads\/2023\/12\/vystup-z-prikladu-950-730-768x590.webp 768w\" sizes=\"auto, (max-width: 950px) 100vw, 950px\" \/><\/p>\n<h2>Conclusion<\/h2>\n<p>The <strong>Flyweight<\/strong> design pattern is used in situations where we need to cache and reuse object instances that are similar. It is mainly aimed at optimizing the overhead of object creation and their memory requirements.<\/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\/2023\/12\/Flyweight.zip\">Download the Java Flyweight 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 latest <a href=\"https:\/\/msg-life.sk\/en\/jobs\/\">job offers<\/a>.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>What is the Flyweight design pattern and what is it for? Read our new article and download the sample code.<\/p>\n","protected":false},"author":14,"featured_media":2250,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_acf_changed":false,"footnotes":""},"categories":[57],"tags":[],"class_list":["post-2373","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\/2373","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=2373"}],"version-history":[{"count":4,"href":"https:\/\/msgprogramator.sk\/en\/wp-json\/wp\/v2\/posts\/2373\/revisions"}],"predecessor-version":[{"id":5213,"href":"https:\/\/msgprogramator.sk\/en\/wp-json\/wp\/v2\/posts\/2373\/revisions\/5213"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/msgprogramator.sk\/en\/wp-json\/wp\/v2\/media\/2250"}],"wp:attachment":[{"href":"https:\/\/msgprogramator.sk\/en\/wp-json\/wp\/v2\/media?parent=2373"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/msgprogramator.sk\/en\/wp-json\/wp\/v2\/categories?post=2373"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/msgprogramator.sk\/en\/wp-json\/wp\/v2\/tags?post=2373"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}