{"id":1975,"date":"2023-11-03T09:44:07","date_gmt":"2023-11-03T09:44:07","guid":{"rendered":"https:\/\/msgprogramator.testovacka.sk\/java-design-patterns-design-patterns-composite\/"},"modified":"2025-11-06T10:48:24","modified_gmt":"2025-11-06T10:48:24","slug":"java-composite-design-pattern","status":"publish","type":"post","link":"https:\/\/msgprogramator.sk\/en\/java-composite-design-pattern\/","title":{"rendered":"Java design pattern Composite"},"content":{"rendered":"<p>Today we will take a look at another <strong>Java<\/strong> <strong>design pattern<\/strong> from the category of <strong>structural patterns<\/strong> &#8211; Composite. Design patterns in this category deal with class structure such as <strong>inheritance<\/strong> and <strong>composition<\/strong>.<\/p>\n<p>Read more about design patterns:<\/p>\n<ul>\n<li><a href=\"https:\/\/msgprogramator.sk\/en\/java-singleton\/\">Singleton design pattern<\/a><\/li>\n<li><a href=\"https:\/\/msgprogramator.sk\/en\/java-builder\/\">Builder design pattern<\/a><\/li>\n<li><a href=\"https:\/\/msgprogramator.sk\/en\/java-prototype\/\">Prototype design pattern<\/a><\/li>\n<li><a href=\"https:\/\/msgprogramator.sk\/en\/java-factory\/\">Factory design pattern<\/a><\/li>\n<li><a href=\"https:\/\/msgprogramator.sk\/en\/java-abstract-factory\/\">Abstract Factory design pattern<\/a><\/li>\n<li><a href=\"https:\/\/msgprogramator.sk\/en\/java-bridge\/\">Bridge design pattern<\/a><\/li>\n<\/ul>\n<h2>What is the Composite design pattern?<\/h2>\n<p><strong>Composite<\/strong> is a design pattern that is used to create a tree structure of objects that allows the client to work with individual objects and their groupings (composites) in the same way because they have the same interface.<\/p>\n<h2>What problem does the Composite design pattern solve?<\/h2>\n<p>When working with a tree structure, developers often have to distinguish between a leaf node and a branch. This makes the code more complex and therefore more error prone. The solution is an interface that allows complex and primitive objects to be handled uniformly.<\/p>\n<p>The problem that Composite solves is the need to work with objects and their composites in a uniform way. This allows the client to recursively traverse and manipulate the entire tree structure, without the need to distinguish between individual objects and their groupings.<\/p>\n<h2>Example of Composite implementation in Java<\/h2>\n<p>Now we will show how to implement the Composite pattern in Java. We will create a complex tree structure composed of both individual objects (leaves) and compositions of objects (branches). By using the Composite pattern, we achieve uniform execution of operations on individual parts of the tree regardless of type.<\/p>\n<p>The <em>CastStromu<\/em> interface represents a common interface for both leaf nodes (<em>Leaf<\/em>) and composite nodes (<em>Branch<\/em>). This interface defines the <em>vykonajOperaciu()<\/em> method, which is key to this pattern.<\/p>\n<p><strong><u>CastStromu.java<\/u><\/strong><\/p>\n<pre><code class=\"language-java\" data-line=\"\">package designpatterns;\n\n\/\/ CastStromu - rozhranie pre v\u0161etky objekty v strome\npublic interface CastStromu {\n    void vykonajOperaciu();\n}<\/code><\/pre>\n<p>The <em>List<\/em> class represents the leaf component in the hierarchy. It implements the <em>CastStrom<\/em> interface and provides an implementation of the <em>vykonajOperaciu()<\/em> method. The leaf components have no child elements and perform operations.<\/p>\n<p><strong><u>List.java<\/u><\/strong><\/p>\n<pre><code class=\"language-java\" data-line=\"\">package designpatterns;\n\n\/\/ List - konkr\u00e9tna \u010das\u0165 stromu reprezentuj\u00faca list v strome\npublic class List implements CastStromu {\n    private String id;\n\n    public List(String id) {\n        this.id = id;\n    }\n\n    public void vykonajOperaciu() {\n        System.out.println(&quot;Vykon\u00e1vam oper\u00e1ciu na liste s n\u00e1zvom: &quot; + id);\n    }\n}<\/code><\/pre>\n<p>The <em>Branch<\/em> class represents a composite component in the hierarchy. It also implements the <em>CastStromu<\/em> interface and maintains a collection (<em>castiStromu<\/em>) of child components, which can be either leaf components or other composite components.<\/p>\n<p>The <em>pridajCast()<\/em> method allows you to add child components and thus construct a hierarchical structure.<\/p>\n<p><strong><u>Branch.java<\/u><\/strong><\/p>\n<pre><code class=\"language-java\" data-line=\"\">package designpatterns;\n\nimport java.util.ArrayList;\n\n\/\/ Konkr\u00e9tna \u010das\u0165 stromu reprezentuj\u00faca vetvu v strome\npublic class Vetva implements CastStromu {\n    private String id;\n    private java.util.List&lt;CastStromu&gt; castiStromu = new ArrayList&lt;&gt;();\n\n    public Vetva(String id) {\n        this.id = id;\n    }\n\n    public void pridajCast(CastStromu cast) {\n        castiStromu.add(cast);\n    }\n\n    public void vykonajOperaciu() {\n        System.out.println(&quot;Vykon\u00e1vam oper\u00e1ciu na vetve s n\u00e1zvom: &quot; + id);\n        for (CastStromu cast : castiStromu) {\n            cast.vykonajOperaciu();\n        }\n    }\n}<\/code><\/pre>\n<p>In the main method, an instance of the root composite component (kmenovaVetva) is created and child components (both leaf and composite) are added to it.<\/p>\n<p>When the <em>vykonajOperaciu()<\/em> method is called on a trunk component (kmenovaVetva), it recursively calls the <em>vykonajOperaciu()<\/em> method on all child components, resulting in operations being performed on the entire structure.<\/p>\n<p><strong><u>Main.java<\/u><\/strong><\/p>\n<pre><code class=\"language-java\" data-line=\"\">import designpatterns.*;\n\npublic class Main {\n    public static void main(String[] args) {\n        \/\/ Vytvor\u00ed strom z listov a vetiev\n        System.out.println(&quot;Sklad\u00e1m strom z kme\u0148a, listov a vetiev.&quot;);\n        List list1 = new List(&quot;List 1&quot;);\n        List list2 = new List(&quot;List 2&quot;);\n        List list3 = new List(&quot;List 3&quot;);\n\n        Vetva vetva1 = new Vetva(&quot;Vetva 1&quot;);\n        vetva1.pridajCast(list1);\n        vetva1.pridajCast(list2);\n\n        Vetva vetva2 = new Vetva(&quot;Vetva 2&quot;);\n        vetva2.pridajCast(list3);\n\n        Vetva kmenovaVetva = new Vetva(&quot;Kme\u0148&quot;);\n        kmenovaVetva.pridajCast(vetva1);\n        kmenovaVetva.pridajCast(vetva2);\n\n        \/\/ Vykon\u00e1va oper\u00e1ciu na celej stromovej \u0161trukt\u00fare\n        kmenovaVetva.vykonajOperaciu();\n    }\n}<\/code><\/pre>\n<p>The output of this example is:<\/p>\n<figure id=\"attachment_1929\" aria-describedby=\"caption-attachment-1929\" style=\"width: 800px\" class=\"wp-caption aligncenter\"><img loading=\"lazy\" decoding=\"async\" class=\"size-full wp-image-1561\" src=\"https:\/\/msgprogramator.sk\/wp-content\/uploads\/2023\/11\/main-java-vystup-prikladu-800-470.webp\" alt=\"Java code output from the Composite example\" width=\"800\" height=\"470\" srcset=\"https:\/\/msgprogramator.sk\/wp-content\/uploads\/2023\/11\/main-java-vystup-prikladu-800-470.webp 800w, https:\/\/msgprogramator.sk\/wp-content\/uploads\/2023\/11\/main-java-vystup-prikladu-800-470-300x176.webp 300w, https:\/\/msgprogramator.sk\/wp-content\/uploads\/2023\/11\/main-java-vystup-prikladu-800-470-768x451.webp 768w\" sizes=\"auto, (max-width: 800px) 100vw, 800px\" \/><figcaption id=\"caption-attachment-1929\" class=\"wp-caption-text\">code output<\/figcaption><\/figure>\n<h2>Java Composite conclusion<\/h2>\n<p>The Composite design pattern is used in situations where it is necessary to work uniformly with individual objects and their groupings.<\/p>\n<p>We have prepared the files with the above example in the form of code that you can run directly in Java. Download the <a href=\"https:\/\/msgprogramator.sk\/wp-content\/uploads\/2023\/11\/Composite.zip\">Java Composite code here.<\/a><\/p>\n","protected":false},"excerpt":{"rendered":"<p>What is Composite Design Pattern and what is it for? Read our new article and download the sample code.<\/p>\n","protected":false},"author":14,"featured_media":1927,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_acf_changed":false,"footnotes":""},"categories":[57],"tags":[],"class_list":["post-1975","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\/1975","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=1975"}],"version-history":[{"count":15,"href":"https:\/\/msgprogramator.sk\/en\/wp-json\/wp\/v2\/posts\/1975\/revisions"}],"predecessor-version":[{"id":9394,"href":"https:\/\/msgprogramator.sk\/en\/wp-json\/wp\/v2\/posts\/1975\/revisions\/9394"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/msgprogramator.sk\/en\/wp-json\/wp\/v2\/media\/1927"}],"wp:attachment":[{"href":"https:\/\/msgprogramator.sk\/en\/wp-json\/wp\/v2\/media?parent=1975"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/msgprogramator.sk\/en\/wp-json\/wp\/v2\/categories?post=1975"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/msgprogramator.sk\/en\/wp-json\/wp\/v2\/tags?post=1975"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}