{"id":2375,"date":"2023-08-25T16:05:57","date_gmt":"2023-08-25T16:05:57","guid":{"rendered":"https:\/\/msgprogramator.sk\/?p=2375"},"modified":"2025-07-07T10:57:21","modified_gmt":"2025-07-07T10:57:21","slug":"java-factory","status":"publish","type":"post","link":"https:\/\/msgprogramator.sk\/en\/java-factory\/","title":{"rendered":"Java design pattern Factory"},"content":{"rendered":"<p>In this article, we will look at another <strong>Java <\/strong><strong>design pattern<\/strong> from the category of patterns designed for creating objects (<strong>creational patterns<\/strong>) &#8211; Factory.<\/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-abstract-factory\/\">Abstract Factory design pattern<\/a><\/li>\n<li><a href=\"https:\/\/msgprogramator.sk\/en\/java-adapter\/\">Adapter design pattern<\/a><\/li>\n<\/ul>\n<h2>What is the Factory design pattern?<\/h2>\n<p>The <strong>Factory<\/strong> <em>design pattern<\/em> is a software design pattern whose main goal is to provide a simple and flexible way to create class instances without having to directly specify specific classes in client code.<\/p>\n<h2>What problem does the Factory design pattern solve?<\/h2>\n<p>If we have classes that implement or are derived from a common interface, we want to be able to create instances of those classes without having to directly mention a specific class. This is useful if we don&#8217;t want the client code to be bound to a specific implementation, but want to retrieve an object based on some parameter or condition.<\/p>\n<h2>Example of Factory implementation in Java<\/h2>\n<p>Now we will show how to implement the Factory pattern in Java. This example illustrates how the Factory pattern allows you to create different types of objects (chocolates) using a single factory class without having to directly specify specific classes in client code.<\/p>\n<p><strong><u>Chocolate.java<\/u><\/strong><\/p>\n<p>In this example, we have created an abstract class Chocolate to represent chocolate.<\/p>\n<pre><code class=\"language-java\" data-line=\"\">package designpatterns;\n\n\/\/ Abstract class representing chocolate\npublic abstract class Chocolate {\n    public abstract void taste();\n}<\/code><\/pre>\n<p><strong><u>Milka.java, Lindt.java<\/u><\/strong><\/p>\n<p>We then implemented two concrete classes, Milka and Lindt, which extend the abstract class Chocolate. Each of these classes defines its own implementation of the ochutnat() method.<\/p>\n<pre><code class=\"language-java\" data-line=\"\">package designpatterns;\n\n\/\/ Concrete implementation of Lindt brand chocolate\npublic class Lindt extends Chocolate {\n    @Override\n    public void taste() {\n        System.out.println(&quot;Lindt: Velvety and luxurious taste&quot;);\n    }\n}\n\n\/\/ Concrete implementation of Milka brand chocolate\npublic class Milka extends Chocolate {\n    @Override\n    public void taste() {\n        System.out.println(&quot;Milka: Sweet and milky taste&quot;);\n    }\n}<\/code><\/pre>\n<p><strong><u>C<\/u><\/strong><strong><u>hocolateFactory.java<\/u><\/strong><\/p>\n<p>Next, we created the ChocolateFactory class, which is used to create instances of chocolate based on the brand. The makeChocolate(String znacka) method creates a chocolate according to the given parameter znacka (= brand).  If the brand is <em>Milka<\/em>, an instance of the <em>Milka<\/em> class is created, if the brand is <em>Lindt<\/em>, an instance of the <em>Lindt<\/em> class is created. If an unknown tag is specified, an <em>IllegalArgumentException<\/em> is thrown.<\/p>\n<pre><code class=\"language-java\" data-line=\"\">package designpatterns;\n\n\/\/ Factory class for chocolate production\npublic class ChocolateFactory {\n    public Chocolate makeChocolate(String brand) {\n        if(brand.equalsIgnoreCase(&quot;Milka&quot;)) {\n            return new Milka();\n        }\n        else if(brand.equalsIgnoreCase(&quot;Lindt&quot;)) {\n            return new Lindt();\n        }\n        else {\n            throw new IllegalArgumentException(&quot;Unknown chocolate brand: &quot; + brand);\n        }\n    }\n}<\/code><\/pre>\n<p><strong><u>Main.java<\/u><\/strong><\/p>\n<p>We created an instance of ChocolateFactory in the client code, and used it to create and taste Milka and Lindt chocolate.<\/p>\n<pre><code class=\"language-java\" data-line=\"\">import designpatterns.*;\n\n\/\/ Example\npublic class Main {\n    public static void main(String[] args) {\n        ChocolateFactory factory = new ChocolateFactory();\n\n        \/\/ Making and tasting of Milka brand chocolate\n        Chocolate milka = factory.makeChocolate(&quot;Milka&quot;);\n        milka.taste();\n\n        \/\/ Making and tasting of Lindt brand chocolate\n        Chocolate lindt = factory.makeChocolate(&quot;Lindt&quot;);\n        lindt.taste();\n    }\n}<\/code><\/pre>\n<p>Output of the program<\/p>\n<figure id=\"attachment_4396\" aria-describedby=\"caption-attachment-4396\" style=\"width: 440px\" class=\"wp-caption aligncenter\"><img loading=\"lazy\" decoding=\"async\" class=\"size-full wp-image-4395\" src=\"https:\/\/msgprogramator.sk\/wp-content\/uploads\/2023\/08\/Factory-design-pattern-eng-output.webp\" alt=\"factory design pattern program output\" width=\"440\" height=\"174\" srcset=\"https:\/\/msgprogramator.sk\/wp-content\/uploads\/2023\/08\/Factory-design-pattern-eng-output.webp 440w, https:\/\/msgprogramator.sk\/wp-content\/uploads\/2023\/08\/Factory-design-pattern-eng-output-300x119.webp 300w\" sizes=\"auto, (max-width: 440px) 100vw, 440px\" \/><figcaption id=\"caption-attachment-4396\" class=\"wp-caption-text\">output of the example Factory<\/figcaption><\/figure>\n<p>We have prepared the files with the above mentioned Java Factory example in the form of code that you can run directly in Java. <a href=\"https:\/\/msgprogramator.sk\/wp-content\/uploads\/2024\/09\/Factory_Eng.zip\">Download the 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 a job, read more about <a href=\"https:\/\/msgprogramator.sk\/en\/it-salary-developer\/\">developer salary<\/a> and check out our latest <a href=\"https:\/\/msg-life.sk\/en\/jobs\/\">job offers<\/a>.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>In this article you will learn what a Factory design pattern is and how to create one.<\/p>\n","protected":false},"author":14,"featured_media":1873,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_acf_changed":false,"footnotes":""},"categories":[57],"tags":[],"class_list":["post-2375","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\/2375","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=2375"}],"version-history":[{"count":6,"href":"https:\/\/msgprogramator.sk\/en\/wp-json\/wp\/v2\/posts\/2375\/revisions"}],"predecessor-version":[{"id":5212,"href":"https:\/\/msgprogramator.sk\/en\/wp-json\/wp\/v2\/posts\/2375\/revisions\/5212"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/msgprogramator.sk\/en\/wp-json\/wp\/v2\/media\/1873"}],"wp:attachment":[{"href":"https:\/\/msgprogramator.sk\/en\/wp-json\/wp\/v2\/media?parent=2375"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/msgprogramator.sk\/en\/wp-json\/wp\/v2\/categories?post=2375"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/msgprogramator.sk\/en\/wp-json\/wp\/v2\/tags?post=2375"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}