<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Sota</title>
    <description>The latest articles on DEV Community by Sota (@sota_333ad4b72095606ab40c).</description>
    <link>https://dev.to/sota_333ad4b72095606ab40c</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F2280987%2Fc073deac-258d-44a4-98ef-d2ad275afba2.jpg</url>
      <title>DEV Community: Sota</title>
      <link>https://dev.to/sota_333ad4b72095606ab40c</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/sota_333ad4b72095606ab40c"/>
    <language>en</language>
    <item>
      <title>Understanding Java Enums by Rebuilding One</title>
      <dc:creator>Sota</dc:creator>
      <pubDate>Sun, 18 Jan 2026 15:53:14 +0000</pubDate>
      <link>https://dev.to/sota_333ad4b72095606ab40c/understanding-java-enums-by-rebuilding-one-4c8p</link>
      <guid>https://dev.to/sota_333ad4b72095606ab40c/understanding-java-enums-by-rebuilding-one-4c8p</guid>
      <description>&lt;h2&gt;
  
  
  Enum is just a class
&lt;/h2&gt;

&lt;p&gt;Have you ever noticed that you can define an enum-like class &lt;em&gt;without&lt;/em&gt; using the &lt;code&gt;enum&lt;/code&gt; keyword, just like a normal class you write in everyday development?&lt;br&gt;&lt;br&gt;
If not, this article is worth a look!&lt;/p&gt;
&lt;h2&gt;
  
  
  What is an Enum?
&lt;/h2&gt;

&lt;p&gt;An enum is a type that defines a &lt;strong&gt;fixed set of predefined, type-safe constants&lt;/strong&gt;, optionally with behavior.&lt;/p&gt;

&lt;p&gt;Enums were introduced in &lt;strong&gt;Java 5&lt;/strong&gt;. Before that, developers implemented enum-like classes manually.&lt;br&gt;&lt;br&gt;
Let’s travel back to that time to better understand how enums actually work under the hood.&lt;/p&gt;
&lt;h2&gt;
  
  
  Code example
&lt;/h2&gt;
&lt;h3&gt;
  
  
  Basic enum
&lt;/h3&gt;


&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="kd"&gt;enum&lt;/span&gt; &lt;span class="nc"&gt;Fruit&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
    &lt;span class="no"&gt;APPLE&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt;
    &lt;span class="no"&gt;BANANA&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;
&lt;span class="o"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;p&gt;Let’s start with a simple example. This defines a type Fruit with exactly two allowed instances: APPLE and BANANA.&lt;/p&gt;

&lt;p&gt;Although Java provides the enum keyword, the core idea behind an enum is not magical.&lt;br&gt;
It can be expressed using a regular class with a few strict rules.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kd"&gt;final&lt;/span&gt; &lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;Fruit&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
    &lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kd"&gt;static&lt;/span&gt; &lt;span class="kd"&gt;final&lt;/span&gt; &lt;span class="nc"&gt;Fruit&lt;/span&gt; &lt;span class="no"&gt;APPLE&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;Fruit&lt;/span&gt;&lt;span class="o"&gt;();&lt;/span&gt;
    &lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kd"&gt;static&lt;/span&gt; &lt;span class="kd"&gt;final&lt;/span&gt; &lt;span class="nc"&gt;Fruit&lt;/span&gt; &lt;span class="no"&gt;BANANA&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;Fruit&lt;/span&gt;&lt;span class="o"&gt;();&lt;/span&gt;

    &lt;span class="kd"&gt;private&lt;/span&gt; &lt;span class="nf"&gt;Fruit&lt;/span&gt;&lt;span class="o"&gt;()&lt;/span&gt; &lt;span class="o"&gt;{};&lt;/span&gt;
&lt;span class="o"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;APPLE and BANANA are both instances of the Fruit class. Each of them is a singleton, meaning there is exactly one instance per constant. In other words, only one APPLE object and one BANANA object ever exist in the JVM.&lt;br&gt;
Because these instances are created as &lt;code&gt;public static final&lt;/code&gt; fields and the constructor is private, no additional instances can be created.&lt;/p&gt;
&lt;h3&gt;
  
  
  Adding a property
&lt;/h3&gt;

&lt;p&gt;Let's add a property.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kd"&gt;enum&lt;/span&gt; &lt;span class="nc"&gt;Fruit&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
    &lt;span class="no"&gt;APPLE&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;200&lt;/span&gt;&lt;span class="o"&gt;),&lt;/span&gt;
    &lt;span class="no"&gt;BANANA&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;150&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;

    &lt;span class="kd"&gt;private&lt;/span&gt; &lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;price&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;

    &lt;span class="kd"&gt;private&lt;/span&gt; &lt;span class="nf"&gt;Fruit&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;price&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
        &lt;span class="k"&gt;this&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;price&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;price&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;
    &lt;span class="o"&gt;}&lt;/span&gt;
&lt;span class="o"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The equivalent code without the enum keyword is shown below.&lt;br&gt;
Now we have a price property, and the constructor receives a value and assigns it to that property.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kd"&gt;final&lt;/span&gt; &lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;Fruit&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
    &lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kd"&gt;static&lt;/span&gt; &lt;span class="kd"&gt;final&lt;/span&gt; &lt;span class="nc"&gt;Fruit&lt;/span&gt; &lt;span class="no"&gt;APPLE&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;Fruit&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;200&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
    &lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kd"&gt;static&lt;/span&gt; &lt;span class="kd"&gt;final&lt;/span&gt; &lt;span class="nc"&gt;Fruit&lt;/span&gt; &lt;span class="no"&gt;BANANA&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;Fruit&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;150&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;

    &lt;span class="kd"&gt;private&lt;/span&gt; &lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;price&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;

    &lt;span class="kd"&gt;private&lt;/span&gt; &lt;span class="nf"&gt;Fruit&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;price&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
        &lt;span class="k"&gt;this&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;price&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;price&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;
    &lt;span class="o"&gt;};&lt;/span&gt;
&lt;span class="o"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Adding a method
&lt;/h3&gt;

&lt;p&gt;Finally, let's add a method that returns the price with tax included.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kd"&gt;enum&lt;/span&gt; &lt;span class="nc"&gt;Fruit&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
    &lt;span class="no"&gt;APPLE&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;200&lt;/span&gt;&lt;span class="o"&gt;),&lt;/span&gt;
    &lt;span class="no"&gt;BANANA&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;150&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;

    &lt;span class="kd"&gt;private&lt;/span&gt; &lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;price&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;

    &lt;span class="kd"&gt;private&lt;/span&gt; &lt;span class="nf"&gt;Fruit&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;price&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
        &lt;span class="k"&gt;this&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;price&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;price&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;
    &lt;span class="o"&gt;}&lt;/span&gt;

    &lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kt"&gt;double&lt;/span&gt; &lt;span class="nf"&gt;addTax&lt;/span&gt;&lt;span class="o"&gt;()&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;price&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;price&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt; &lt;span class="mf"&gt;0.1&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt; &lt;span class="c1"&gt;// add 10% taxes&lt;/span&gt;
    &lt;span class="o"&gt;}&lt;/span&gt;
&lt;span class="o"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The equivalent implementation using a regular class:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kd"&gt;final&lt;/span&gt; &lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;Fruit&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
    &lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kd"&gt;static&lt;/span&gt; &lt;span class="kd"&gt;final&lt;/span&gt; &lt;span class="nc"&gt;Fruit&lt;/span&gt; &lt;span class="no"&gt;APPLE&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;Fruit&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;200&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
    &lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kd"&gt;static&lt;/span&gt; &lt;span class="kd"&gt;final&lt;/span&gt; &lt;span class="nc"&gt;Fruit&lt;/span&gt; &lt;span class="no"&gt;BANANA&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;Fruit&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;150&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;

    &lt;span class="kd"&gt;private&lt;/span&gt; &lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;price&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;

    &lt;span class="kd"&gt;private&lt;/span&gt; &lt;span class="nf"&gt;Fruit&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;price&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
        &lt;span class="k"&gt;this&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;price&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;price&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;
    &lt;span class="o"&gt;};&lt;/span&gt;

    &lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kt"&gt;double&lt;/span&gt; &lt;span class="nf"&gt;addTax&lt;/span&gt;&lt;span class="o"&gt;()&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;price&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;price&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt; &lt;span class="mf"&gt;0.1&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
    &lt;span class="o"&gt;}&lt;/span&gt;
&lt;span class="o"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;This demonstrates that an enum is fundamentally the same as a regular class, expressed using different syntax and enforced by the language. Each enum constant is a singleton instance, and the enum keyword exists to guarantee this pattern safely and conveniently.&lt;/p&gt;

</description>
      <category>programming</category>
      <category>java</category>
    </item>
    <item>
      <title>Interface vs Abstract class</title>
      <dc:creator>Sota</dc:creator>
      <pubDate>Sun, 18 Jan 2026 05:24:50 +0000</pubDate>
      <link>https://dev.to/sota_333ad4b72095606ab40c/interface-vs-abstract-class-1gi7</link>
      <guid>https://dev.to/sota_333ad4b72095606ab40c/interface-vs-abstract-class-1gi7</guid>
      <description>&lt;h2&gt;
  
  
  Interface or Abstract Class?
&lt;/h2&gt;

&lt;p&gt;They are very similar, and therefore it can be confusing to know when to use each one. I’m going to answer this question in this article.&lt;/p&gt;

&lt;h2&gt;
  
  
  Short answer
&lt;/h2&gt;

&lt;p&gt;Use an interface when…&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;there is no default behavior&lt;/li&gt;
&lt;li&gt;you want to force subclasses (implementations) to implement the behavior&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Use an abstract class when…&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;you want to define default behavior&lt;/li&gt;
&lt;li&gt;you want to control the process flow, while the individual steps of the process are implemented by subclasses&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Code Example
&lt;/h2&gt;

&lt;h3&gt;
  
  
  Interface
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kd"&gt;interface&lt;/span&gt; &lt;span class="nc"&gt;IAnimal&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
    &lt;span class="kt"&gt;void&lt;/span&gt; &lt;span class="nf"&gt;bark&lt;/span&gt;&lt;span class="o"&gt;();&lt;/span&gt;
&lt;span class="o"&gt;}&lt;/span&gt;

&lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;Dog&lt;/span&gt; &lt;span class="kd"&gt;implements&lt;/span&gt; &lt;span class="nc"&gt;IAnimal&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
    &lt;span class="nd"&gt;@Override&lt;/span&gt;
    &lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kt"&gt;void&lt;/span&gt; &lt;span class="nf"&gt;bark&lt;/span&gt;&lt;span class="o"&gt;()&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
        &lt;span class="nc"&gt;System&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;out&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;println&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"woof!"&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
    &lt;span class="o"&gt;}&lt;/span&gt;
&lt;span class="o"&gt;}&lt;/span&gt;

&lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kd"&gt;static&lt;/span&gt; &lt;span class="kt"&gt;void&lt;/span&gt; &lt;span class="nf"&gt;main&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;String&lt;/span&gt;&lt;span class="o"&gt;[]&lt;/span&gt; &lt;span class="n"&gt;args&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
    &lt;span class="nc"&gt;IAnimal&lt;/span&gt; &lt;span class="n"&gt;dog&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;Dog&lt;/span&gt;&lt;span class="o"&gt;();&lt;/span&gt;
    &lt;span class="n"&gt;dog&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;bark&lt;/span&gt;&lt;span class="o"&gt;();&lt;/span&gt; &lt;span class="c1"&gt;// "woof!"&lt;/span&gt;
&lt;span class="o"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Because barking sounds depend on the animal, IAnimal does not provide a default behavior. Subclasses have no choice but to override the bark method, since failing to do so causes a compile-time error.&lt;/p&gt;

&lt;h3&gt;
  
  
  Abstract Class
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kd"&gt;abstract&lt;/span&gt; &lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;Animal&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
    &lt;span class="c1"&gt;// The method is final to prevent subclasses from changing the order in which methods are called&lt;/span&gt;
    &lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kd"&gt;final&lt;/span&gt; &lt;span class="kt"&gt;void&lt;/span&gt; &lt;span class="nf"&gt;bark&lt;/span&gt;&lt;span class="o"&gt;()&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
        &lt;span class="n"&gt;takeBreath&lt;/span&gt;&lt;span class="o"&gt;();&lt;/span&gt;
        &lt;span class="n"&gt;makeSounds&lt;/span&gt;&lt;span class="o"&gt;();&lt;/span&gt;
    &lt;span class="o"&gt;}&lt;/span&gt;

    &lt;span class="c1"&gt;// private method as implementation is common for all the animals&lt;/span&gt;
    &lt;span class="kd"&gt;private&lt;/span&gt; &lt;span class="kt"&gt;void&lt;/span&gt; &lt;span class="nf"&gt;takeBreath&lt;/span&gt;&lt;span class="o"&gt;()&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
        &lt;span class="nc"&gt;System&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;out&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;println&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"taking a deep breath..."&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
    &lt;span class="o"&gt;}&lt;/span&gt;

    &lt;span class="c1"&gt;// protected so that subclasses can override while client (main method) cannot call this method directly&lt;/span&gt;
    &lt;span class="c1"&gt;// abstract method to force subclasses to implements this method&lt;/span&gt;
    &lt;span class="kd"&gt;protected&lt;/span&gt; &lt;span class="kd"&gt;abstract&lt;/span&gt; &lt;span class="kt"&gt;void&lt;/span&gt; &lt;span class="nf"&gt;makeSounds&lt;/span&gt;&lt;span class="o"&gt;();&lt;/span&gt;
&lt;span class="o"&gt;}&lt;/span&gt;

&lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;Cat&lt;/span&gt; &lt;span class="kd"&gt;extends&lt;/span&gt; &lt;span class="nc"&gt;Animal&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
    &lt;span class="nd"&gt;@Override&lt;/span&gt;
    &lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kt"&gt;void&lt;/span&gt; &lt;span class="nf"&gt;makeSounds&lt;/span&gt;&lt;span class="o"&gt;()&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
        &lt;span class="nc"&gt;System&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;out&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;println&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"meow!"&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
    &lt;span class="o"&gt;}&lt;/span&gt;
&lt;span class="o"&gt;}&lt;/span&gt;

&lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kd"&gt;static&lt;/span&gt; &lt;span class="kt"&gt;void&lt;/span&gt; &lt;span class="nf"&gt;main&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;String&lt;/span&gt;&lt;span class="o"&gt;[]&lt;/span&gt; &lt;span class="n"&gt;args&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
    &lt;span class="nc"&gt;Animal&lt;/span&gt; &lt;span class="n"&gt;car&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;Cat&lt;/span&gt;&lt;span class="o"&gt;();&lt;/span&gt;
    &lt;span class="n"&gt;cat&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;bark&lt;/span&gt;&lt;span class="o"&gt;();&lt;/span&gt; &lt;span class="c1"&gt;// "meow!"&lt;/span&gt;
&lt;span class="o"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;I want to control the makeSounds process so that all animals take a breath first and then bark, this flow should remain constant. However, as in the previous example, barking sounds depend on the animal, so the bark method should be overridden by subclasses.&lt;/p&gt;

</description>
      <category>java</category>
      <category>programming</category>
    </item>
    <item>
      <title>How to call third-party API in Spring Boot</title>
      <dc:creator>Sota</dc:creator>
      <pubDate>Thu, 23 Jan 2025 13:20:29 +0000</pubDate>
      <link>https://dev.to/sota_333ad4b72095606ab40c/how-to-call-third-party-api-in-spring-boot-1j21</link>
      <guid>https://dev.to/sota_333ad4b72095606ab40c/how-to-call-third-party-api-in-spring-boot-1j21</guid>
      <description>&lt;h2&gt;
  
  
  Overview
&lt;/h2&gt;

&lt;p&gt;I will introduce how to call third-party API in Spring Boot project. We'll send GET request to this resource &lt;a href="https://sampleapis.com/api-list/coffee" rel="noopener noreferrer"&gt;https://sampleapis.com/api-list/coffee&lt;/a&gt;, then display response data in view (browser).&lt;/p&gt;

&lt;h2&gt;
  
  
  Prerequisites
&lt;/h2&gt;

&lt;p&gt;You need these knowledge at basic level:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Java&lt;/li&gt;
&lt;li&gt;Spring Boot&lt;/li&gt;
&lt;li&gt;Thymeleaf&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Development process
&lt;/h2&gt;

&lt;h3&gt;
  
  
  Create Project
&lt;/h3&gt;

&lt;p&gt;Go to &lt;a href="https://start.spring.io/" rel="noopener noreferrer"&gt;https://start.spring.io/&lt;/a&gt; and generate a project with these dependencies:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fiamqxd04tn9ccg38zgjs.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fiamqxd04tn9ccg38zgjs.jpg" alt="Image description" width="800" height="358"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Unzip the file and open the project in your code editor. I use Intellij community edition.&lt;/p&gt;

&lt;h3&gt;
  
  
  Create Controller
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import com.myproject.apidemo.Coffee;

import org.springframework.core.ParameterizedTypeReference;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.reactive.function.client.WebClient;

@Controller
public class CoffeeController {

    @GetMapping("/coffee")
    public String coffee(Model model) {
        String url = "https://api.sampleapis.com/coffee/hot";

        WebClient.Builder builder = WebClient.builder();

        String coffeeList = builder.build()
                .get()
                .uri(url)
                .retrieve()
                .bodyToMono(String.class)
                .block();

        System.out.println("---------------------");
        System.out.println(coffeeList);

        model.addAttribute("coffeeList", coffeeList);

        return "coffee";
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If you can't import some of them, then one possible problem is Maven doesn't load your pom.xml file correctly. Reloading the project resolves this issue in my case.&lt;/p&gt;




&lt;p&gt;You can directly type url in your browser and check the response data, it is a list of coffee in JSON format.&lt;/p&gt;

&lt;p&gt;You can map response data to Java object if you want. For this, you need to create Coffee class and define fields that you want to hold as Coffee object. For me, Coffee class has two fields, title and description. This way, when response data maps to Coffee object, the object only holds title and description from response JSON data.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;package com.myproject.todoapp;

public class Coffee {

    String title;

    String description;

    public Coffee() {
    }

    public Coffee(String title, String description) {
        this.title = title;
        this.description = description;
    }

    // getters and setters
    // toString method
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import com.myproject.apidemo.Coffee;

import org.springframework.core.ParameterizedTypeReference;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.reactive.function.client.WebClient;

@Controller
public class CoffeeController {

    @GetMapping("/coffee")
    public String coffee(Model model) {
        String url = "https://api.sampleapis.com/coffee/hot";

        WebClient.Builder builder = WebClient.builder();

        List&amp;lt;Coffee&amp;gt; coffeeList = builder.build()
                .get()
                .uri(url)
                .retrieve()
                .bodyToMono(new ParameterizedTypeReference&amp;lt;List&amp;lt;Coffee&amp;gt;&amp;gt;() {
                })
                .block();

        System.out.println("---------------------");
        System.out.println(coffeeList);

        model.addAttribute("coffeeList", coffeeList);

        return "coffee";
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In this tutorial, I prefer converting the response data to Coffee object, so I stick to second version implementation.&lt;/p&gt;

&lt;h3&gt;
  
  
  Create View page
&lt;/h3&gt;

&lt;p&gt;Finally we need view page just to display list of coffee:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;!doctype html&amp;gt;
&amp;lt;html lang="en" xmlns:th="http://www.thymeleaf.org"&amp;gt;
&amp;lt;head&amp;gt;
    &amp;lt;meta charset="UTF-8"&amp;gt;
    &amp;lt;meta name="viewport" content="width=device-width, initial-scale=1"&amp;gt;
    &amp;lt;title&amp;gt;Coffee&amp;lt;/title&amp;gt;
&amp;lt;/head&amp;gt;
&amp;lt;body&amp;gt;

&amp;lt;h3&amp;gt;Coffee List&amp;lt;/h3&amp;gt;

&amp;lt;table&amp;gt;
    &amp;lt;tbody&amp;gt;
    &amp;lt;tr th:each="coffee: ${coffeeList}"&amp;gt;
        &amp;lt;td th:text="${coffee.title}"&amp;gt;&amp;lt;/td&amp;gt;
        &amp;lt;td th:text="${coffee.description}"&amp;gt;&amp;lt;/td&amp;gt;
    &amp;lt;/tr&amp;gt;
    &amp;lt;/tbody&amp;gt;
&amp;lt;/table&amp;gt;

&amp;lt;/body&amp;gt;
&amp;lt;/html&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Done! Now you should be able to get data from &lt;a href="http://localhost:8080/coffee" rel="noopener noreferrer"&gt;http://localhost:8080/coffee&lt;/a&gt;.&lt;/p&gt;

&lt;h2&gt;
  
  
  Refactoring code
&lt;/h2&gt;

&lt;p&gt;Although we could successfully call the API, there's a room for improvement. Currently coffee method instantiates WebClient.Builder object each time when it gets called. This is unnecessary overhead. Better implementation is creating separate file that configures WebClient.Builder.&lt;/p&gt;

&lt;p&gt;Create configuration file for WebClient:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@Configuration
public class WebClientConfig {

    @Bean
    public WebClient webClient(WebClient.Builder builder) {
        return builder.build();
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Inject the Bean to our Controller class:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    private WebClient webClient;

    @Autowired
    public ToDoListController(WebClient webClient) {
        this.webClient = webClient;
    }

    @GetMapping("/coffee")
    public String coffee(Model model) {
        String url = "https://api.sampleapis.com/coffee/hot";

        List&amp;lt;Coffee&amp;gt; coffeeList = webClient
                .get()
                .uri(url)
                .retrieve()
                .bodyToMono(new ParameterizedTypeReference&amp;lt;List&amp;lt;Coffee&amp;gt;&amp;gt;() {
                })
                .block();

        // other code
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now Spring Boot automatically instantiates and manages WebClient object behind the scene.&lt;/p&gt;

</description>
      <category>api</category>
      <category>webdev</category>
      <category>java</category>
      <category>springboot</category>
    </item>
    <item>
      <title>Proxy Pattern</title>
      <dc:creator>Sota</dc:creator>
      <pubDate>Tue, 10 Dec 2024 14:58:50 +0000</pubDate>
      <link>https://dev.to/sota_333ad4b72095606ab40c/proxy-pattern-42o9</link>
      <guid>https://dev.to/sota_333ad4b72095606ab40c/proxy-pattern-42o9</guid>
      <description>&lt;h2&gt;
  
  
  What is Proxy Pattern?
&lt;/h2&gt;

&lt;blockquote&gt;
&lt;p&gt;Proxy pattern is a structural pattern that provides a surrogate or placeholder for another object to control access to it.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2&gt;
  
  
  When to use it?
&lt;/h2&gt;

&lt;p&gt;There are different types of proxies depending on its specific purpose. But essentially, Proxy pattern is providing a representative for another object.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;Use the &lt;strong&gt;virtual proxy&lt;/strong&gt; when the creation of a resource is expensive, and you want to delay its instantiation until it is actually needed.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Use the &lt;strong&gt;protection proxy&lt;/strong&gt; when you need to control access to an object, typically based on permissions or roles.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Use the &lt;strong&gt;remote proxy&lt;/strong&gt; when you want to represent an object located in a different address space (e.g., on a remote server) and communicate with it as if it were local.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;There are more use cases of Proxy pattern. If you're interested, you can check on the internet for these proxies: &lt;strong&gt;firewall proxy&lt;/strong&gt;, &lt;strong&gt;smart reference proxy&lt;/strong&gt;, &lt;strong&gt;caching proxy&lt;/strong&gt;, &lt;strong&gt;synchronization proxy&lt;/strong&gt;, &lt;strong&gt;complexity hiding proxy&lt;/strong&gt;, &lt;strong&gt;copy-on-write proxy&lt;/strong&gt;, etc.&lt;/p&gt;

&lt;h2&gt;
  
  
  Problem
&lt;/h2&gt;

&lt;p&gt;We're developing bank system. Each customer can access to any customer's account name and account number (to send money for example), but deposit, withdraw, and view balance operations should be only allowed by its account holder.&lt;br&gt;
You might think we could create two classes Holder and NonHolder, then implements corresponding behavior. But notice a customer is a holder of their own bank account and non-holder of other bank account at the same time. We could implement in the way that customer can switch Holder or NonHolder at run time, but it's dangerous because now customers can be a holder of other customer's bank account.&lt;/p&gt;

&lt;p&gt;We need a guardian to protect credential info from non-holder. Can you guess his name? That is the protection proxy!&lt;/p&gt;
&lt;h2&gt;
  
  
  Structure
&lt;/h2&gt;

&lt;p&gt;Before going to Solution section, let's check out general (or static) proxy structure.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fr26rc8mfep3to9z6fqlk.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fr26rc8mfep3to9z6fqlk.png" alt="Image description" width="800" height="379"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;code&gt;Subject&lt;/code&gt; provides a common interface for &lt;code&gt;RealSubject&lt;/code&gt; and &lt;code&gt;Proxy&lt;/code&gt;. In this way, &lt;code&gt;Client&lt;/code&gt; aren't aware they are communicating with &lt;code&gt;RealSubject&lt;/code&gt;, but they are actually interact with &lt;code&gt;Proxy&lt;/code&gt;, that is why Proxy is known as a surrogate or placeholder. When &lt;code&gt;Client&lt;/code&gt; calls a method on &lt;code&gt;Proxy&lt;/code&gt;, &lt;code&gt;Proxy&lt;/code&gt; decides whether it calls the requested method on &lt;code&gt;RealSubject&lt;/code&gt; or does alternative operation such as rejecting the request or displaying text while loading heavy-weight resources.&lt;/p&gt;
&lt;h2&gt;
  
  
  Dynamic Proxy
&lt;/h2&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fepp506evc2mqnvbmdplo.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fepp506evc2mqnvbmdplo.png" alt="Image description" width="800" height="373"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Dynamic proxy is the proxy that allows client to instantiate proxy at runtime. Dynamic proxy can be implemented with Java API Proxy (java.lang.reflect.Proxy).&lt;/p&gt;

&lt;p&gt;The class diagram is a bit different from general proxy structure. Let's steps through the diagram...&lt;/p&gt;

&lt;p&gt;Proxy now consists of two classes, &lt;code&gt;Proxy&lt;/code&gt; and &lt;code&gt;InvocationHandler&lt;/code&gt; classes.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;Client&lt;/code&gt; calls a method on &lt;code&gt;Proxy&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;Proxy&lt;/code&gt; passes the method called by &lt;code&gt;Client&lt;/code&gt; to &lt;code&gt;InvocationHandler&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;InvocationHandler&lt;/code&gt; receives the method from &lt;code&gt;Proxy&lt;/code&gt;, and decides whether it calls the actual method on &lt;code&gt;RealSubject&lt;/code&gt; or does alternative things.&lt;/p&gt;
&lt;h2&gt;
  
  
  Solution
&lt;/h2&gt;

&lt;p&gt;Sorry for making you waiting for a long time, let's get into the solution.&lt;br&gt;
We'll implement dynamic protection proxy.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fyetnasffrgm0kplf4cs3.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fyetnasffrgm0kplf4cs3.png" alt="Image description" width="800" height="416"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;Client&lt;br&gt;
&lt;code&gt;Client&lt;/code&gt; calls a method on &lt;code&gt;Proxy&lt;/code&gt;.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;IBankAccount&lt;br&gt;
&lt;code&gt;Client&lt;/code&gt; talks to &lt;code&gt;Proxy&lt;/code&gt; via &lt;code&gt;IBankAccount&lt;/code&gt; interface.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Proxy&lt;br&gt;
&lt;code&gt;Proxy&lt;/code&gt; receives method calls from &lt;code&gt;Client&lt;/code&gt;. These methods are passed to &lt;code&gt;InvocationHandler&lt;/code&gt;.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;HolderInvocationHandler&lt;br&gt;
&lt;code&gt;HolderInvocationHandler&lt;/code&gt; handles methods calls (invocations) from account holder. Account holder are allowed to access all methods on &lt;code&gt;RealSubject&lt;/code&gt;.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;NonHolderInvocationHandler&lt;br&gt;
&lt;code&gt;NonHolderInvocationHandler&lt;/code&gt; handles methods invocations from non account holder. Non account holder can't access to some of methods such as &lt;code&gt;withdraw()&lt;/code&gt;. For example, if non holder calls &lt;code&gt;withdraw()&lt;/code&gt; on &lt;code&gt;Proxy&lt;/code&gt;, &lt;code&gt;NonHolderInvocationHandler&lt;/code&gt; will receives that call, and block access to &lt;code&gt;RealSubject&lt;/code&gt;.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;
&lt;h2&gt;
  
  
  Implementation in Java
&lt;/h2&gt;


&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public interface IBankAccount {
    // Anyone can access to account's name and number
    String getName();
    String getAccountNumber();

    // deposit, withdraw, viewBalance is only allowed by account holder
    void deposit(double amount);
    void withdraw(double amount);
    void viewBalance();
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public class BankAccount implements IBankAccount {

    private String name;
    private String accountNumber;
    private double balance;

    public BankAccount(String name, String accountNumber, double balance) {
        this.name = name;
        this.accountNumber = accountNumber;
        this.balance = balance;
    }

    @Override
    public String getName() {
        return name;
    }

    @Override
    public String getAccountNumber() {
        return accountNumber;
    }

    @Override
    public void deposit(double amount) {
        balance += amount;
        System.out.println(name + " deposit $" + amount);
    }

    @Override
    public void withdraw(double amount) {
        balance -= amount;
        System.out.println(name + " withdraw $" + amount);
    }

    @Override
    public void viewBalance() {
        System.out.println(name + "'s balance: $" + balance);
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public class HolderInvocationHandler implements InvocationHandler {

    private IBankAccount account;

    public HolderInvocationHandler(IBankAccount account) {
        this.account = account;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        try {
            return method.invoke(account, args);
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        return null;
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public class NonHolderInvocationHandler implements InvocationHandler {

    private IBankAccount account;

    public NonHolderInvocationHandler(IBankAccount account) {
        this.account = account;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws IllegalAccessException {
        try {
            // Anyone can access to other person's name and account number
            if (method.getName().startsWith("get")) {
                method.invoke(account, args);
            } else {
                // Other methods like deposit() are not allowed by anyone but account holder
                throw new IllegalAccessException();
            }
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        return null;
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public class BankAccountTestDrive {

    public static void main(String[] args) {
        BankAccountTestDrive test = new BankAccountTestDrive();
        test.drive();
    }

    public void drive() {
        // Instantiate real subject
        IBankAccount alex = new BankAccount("Alex", "123-abc-456", 500.0);

        System.out.println("-- Testing access via holder proxy --");
        IBankAccount holderProxy = getHolderProxy(alex); // Create proxy
        // Holder proxy allows everything
        System.out.println("Account name: " + holderProxy.getName());
        System.out.println("Account number: " + holderProxy.getAccountNumber());
        holderProxy.deposit(100.0);
        holderProxy.withdraw(50.0);
        holderProxy.viewBalance();

        System.out.println("-- Testing access via non-holder proxy --");
        IBankAccount nonHolderProxy = getNonHolderProxy(alex); // Create proxy
        // Non holder proxy allows getting name and account number
        System.out.println("Account name: " + holderProxy.getName());
        System.out.println("Account number: " + holderProxy.getAccountNumber());
        // Non holder proxy doesn't allow accessing credential info
        try {
            nonHolderProxy.deposit(200.0);
        } catch (Exception e) {
            System.out.println("Can't deposit from non-holder proxy");
        }
        try {
            nonHolderProxy.withdraw(50.0);
        } catch (Exception e) {
            System.out.println("Can't withdraw from non-holder proxy");
        }
        try {
            nonHolderProxy.viewBalance();
        } catch (Exception e) {
            System.out.println("Can't view balance from non-holder proxy");
        }
    }

    // This method takes a IBankAccount object (real subject) and returns a proxy for it.
    // Because proxy has the same interface as the subject, this method returns IBankAccount.
    IBankAccount getHolderProxy(IBankAccount account) {
        // Call static method newProxyInstance on Java API Proxy
        return (IBankAccount) Proxy.newProxyInstance(
                account.getClass().getClassLoader(), // Pass class loader
                account.getClass().getInterfaces(), // Proxy needs to implement the interfaces that real subject implements
                new HolderInvocationHandler(account)); // Pass real subject into the constructor of the invocation handler.
    }

    IBankAccount getNonHolderProxy(IBankAccount account) {
        return (IBankAccount) Proxy.newProxyInstance(
                account.getClass().getClassLoader(),
                account.getClass().getInterfaces(),
                new NonHolderInvocationHandler(account));
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;p&gt;Output:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;-- Testing access via holder proxy --
Account name: Alex
Account number: 123-abc-456
Alex deposit $100.0
Alex withdraw $50.0
Alex's balance: $550.0
-- Testing access via non-holder proxy --
Account name: Alex
Account number: 123-abc-456
Can't deposit from non-holder proxy
Can't withdraw from non-holder proxy
Can't view balance from non-holder proxy
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Pitfalls
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;Proxy increases the number of classes and objects in our design.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Comparison with Decorator Pattern
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;Decorator and Proxy both wraps objects, but their intent is different. Decorator adds small behavior to an object, while Proxy controls access.&lt;/li&gt;
&lt;/ul&gt;




&lt;p&gt;You can check all the design pattern implementations here.&lt;br&gt;
&lt;a href="https://github.com/SotaNoniwa/DesignPattern2" rel="noopener noreferrer"&gt;GitHub Repository&lt;/a&gt;&lt;/p&gt;

</description>
      <category>java</category>
      <category>computerscience</category>
      <category>design</category>
      <category>designpatterns</category>
    </item>
    <item>
      <title>State Pattern</title>
      <dc:creator>Sota</dc:creator>
      <pubDate>Sun, 08 Dec 2024 11:52:03 +0000</pubDate>
      <link>https://dev.to/sota_333ad4b72095606ab40c/state-pattern-3jie</link>
      <guid>https://dev.to/sota_333ad4b72095606ab40c/state-pattern-3jie</guid>
      <description>&lt;h2&gt;
  
  
  What is State Pattern?
&lt;/h2&gt;

&lt;blockquote&gt;
&lt;p&gt;State pattern is a behavioral pattern that allows an object to alter its behavior when its internal state changes. The object will appear to change its class.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2&gt;
  
  
  When to use it?
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;Use State pattern when you have an object whose behavior is different depending on its current state.&lt;/li&gt;
&lt;li&gt;Use State pattern when you want to implement system that represents finite automata.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Problem
&lt;/h2&gt;

&lt;p&gt;We are developing vending machine system. Here's the graph that shows the flow of how vending machine works.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fewhy24fbv78pb3l4t7ec.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fewhy24fbv78pb3l4t7ec.png" alt="Image description" width="731" height="342"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;If you've studied computer science, you may notice it looks like Finite Automata (if you don't know what is FA, no worries, you don't need to know about it to understand State pattern). In the graph, circles represent &lt;strong&gt;states&lt;/strong&gt; and arrows represent &lt;strong&gt;state transaction&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;Anyway, let's begin to code our first version of system.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public class VendingMachine {

    // Vending machine has four states
    final static int OUT_OF_STOCK = 0;
    final static int IDLE = 1;
    final static int HAS_MONEY = 2;
    final static int DRINK_SOLD = 3;

    // When vending machine is placed, it has no drink stocks
    int state = OUT_OF_STOCK; // Our initial state
    int stocks = 0;

    public VendingMachine(int stocks) {
        this.stocks = stocks;
        if (stocks &amp;gt; 0) {
            state = IDLE;
        }
    }

    public void insertMoney() {
        if (state == OUT_OF_STOCK) {
            System.out.println("ERROR: Drink is out of stock");
        } else if (state == IDLE) {
            System.out.println("SUCCESS: You inserted money");
            state = HAS_MONEY;
        } else if (state == HAS_MONEY) {
            System.out.println("ERROR: You already inserted money, you can buy now");
        } else if (state == DRINK_SOLD) {
            System.out.println("ERROR: Please wait, we're dispensing you a drink that you bought");
        }
    }

    public void pressBuyButton() {
        // if statements for each states
    }

    public void pressCancelButton() {
        // if statements for each states
    }

    public void dispenseDrink() {
        // if statements for each states
    }

    public void refill() {
        // if statements for each states
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Can you spot the problems?&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;This code violates open-closed principle.&lt;/li&gt;
&lt;li&gt;This code violates single responsibility principle.&lt;/li&gt;
&lt;li&gt;This code doesn't encapsulate what varies.&lt;/li&gt;
&lt;li&gt;State transitions are not explicit, they are placed under the conditional statements.&lt;/li&gt;
&lt;li&gt;If you add other states or state transitions, it is likely to cause bugs in already working code.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Solution
&lt;/h2&gt;

&lt;p&gt;So, how do we tackle those problems? We are going to turn each state into an object, then implement methods representing state transition from that specific state (object).&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fwn0s665ki3oo3bbku6kg.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fwn0s665ki3oo3bbku6kg.png" alt="Image description" width="800" height="400"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;Client&lt;br&gt;
Client interact with &lt;code&gt;VendingMachine&lt;/code&gt;.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;VendingMechine&lt;br&gt;
This class holds a number of states. By introducing &lt;code&gt;State&lt;/code&gt; interface, it depends on interface not implementation.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;State&lt;br&gt;
Provides common interface for all &lt;code&gt;ConcreteState&lt;/code&gt;.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;ConcreteStates&lt;br&gt;
Each state transaction has different behavior depending on the state. For example, &lt;code&gt;insertMoney&lt;/code&gt; method defined in the &lt;code&gt;Idle&lt;/code&gt; class and the one in the &lt;code&gt;OutOfStock&lt;/code&gt; state behave differently.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Now, lots of if statements in &lt;code&gt;VendingMachine&lt;/code&gt; are removed, and state transitions are explicit (You'll see this in implementation).&lt;/p&gt;

&lt;h2&gt;
  
  
  Structure
&lt;/h2&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fjim8x3y2csvlfhh6vtgq.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fjim8x3y2csvlfhh6vtgq.png" alt="Image description" width="800" height="404"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Does this structure remind you of another pattern? Yes, this class diagram is fundamentally the same as Strategy pattern, but their intents differ. We'll discuss it later.&lt;/p&gt;

&lt;h2&gt;
  
  
  Implementation in Java
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Declare all possible state transition methods
public interface State {
    void insertMoney();
    void pressBuyButton();
    void pressCancelButton();
    void dispenseDrink();
    void refill(int stocks);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public class DrinkSold implements State {

    VendingMachine machine;

    public DrinkSold(VendingMachine machine) {
        this.machine = machine;
    }

    @Override
    public void insertMoney() {
        System.out.println("ERROR: no state transition occurs");
    }

    @Override
    public void pressBuyButton() {
        System.out.println("ERROR: no state transition occurs");
    }

    @Override
    public void pressCancelButton() {
        System.out.println("ERROR: no state transition occurs");
    }

    @Override
    public void dispenseDrink() {
        machine.customerTakesDrink();
        if (machine.getStocks() &amp;gt; 0) {
            System.out.println("SUCCESS: DrinkSold -&amp;gt; Idle");
            machine.setState(machine.getIdle());
        } else {
            System.out.println("SUCCESS: DrinkSold -&amp;gt; OutOfStock");
            machine.setState(machine.getOutOfStock());
        }
    }

    @Override
    public void refill(int stocks) {
        System.out.println("ERROR: no state transition occurs");
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;I'll skip other concrete states because they are similar, but you can check them in my GitHub repo (link to my repo is at the end of this blog).&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public class VendingMachine {

    private State idle;
    private State hasMoney;
    private State drinkSold;
    private State outOfStock;

    private State currentState;
    int stocks = 0;

    public VendingMachine(int stocks) {
        idle = new Idle(this);
        hasMoney = new HasMoney(this);
        drinkSold = new DrinkSold(this);
        outOfStock = new OutOfStock(this);

        this.stocks = stocks;
        if (stocks &amp;gt; 0) {
            currentState = idle;
        } else {
            currentState = outOfStock;
        }
    }

    // State transition methods, actual implementation is delegated to concrete states
    public void insertMoney() {
        currentState.insertMoney();
    }

    public void pressBuyButton() {
        currentState.pressBuyButton();
        currentState.dispenseDrink();
    }

    public void pressCancelButton() {
        currentState.pressCancelButton();
    }

    public void refill(int stocks) {
        currentState.refill(stocks);
    }

    // Method to be used by concrete states to move one state to another
    public void setState(State state) {
        currentState = state;
    }

    // Helper method used when dispensing a drink on DrinkSold state
    public void customerTakesDrink() {
        if (stocks &amp;gt; 0) {
            System.out.println("Customer grab a drink");
            stocks--;
        }
    }

    // Getter for each state
    public State getIdle() {
        return idle;
    }

    public State getHasMoney() {
        return hasMoney;
    }

    public State getDrinkSold() {
        return drinkSold;
    }

    public State getOutOfStock() {
        return outOfStock;
    }

    public int getStocks() {
        return stocks;
    }

    public void setStocks(int stocks) {
        this.stocks = stocks;
    }

    @Override
    public String toString() {
        return "VendingMachine {" +
                "currentState: " + currentState.getClass().getSimpleName() +
                ", stocks: " + stocks +
                '}';
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public class VendingMachineTestDrive {

    public static void main(String[] args) {
        VendingMachine machine = new VendingMachine(2);

        System.out.println(machine);

        System.out.println("-- Customer insert money and cancel the transaction --");
        machine.insertMoney();
        machine.pressCancelButton();

        System.out.println("-- Customer insert money and buy a drink --");
        machine.insertMoney();
        machine.pressBuyButton();

        System.out.println(machine);

        System.out.println("-- Customer insert money and buy a drink --");
        machine.insertMoney();
        machine.pressBuyButton();

        System.out.println(machine);

        System.out.println("-- Customer insert money --");
        machine.insertMoney();

        System.out.println("-- Owner is going to refill drinks --");
        machine.refill(2);
        System.out.println(machine);
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Output:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;VendingMachine {currentState: Idle, stocks: 2}
-- Customer insert money and cancel the transaction --
SUCCESS: Idle -&amp;gt; HasMoney
SUCCESS: HasMoney -&amp;gt; Idle
-- Customer insert money and buy a drink --
SUCCESS: Idle -&amp;gt; HasMoney
SUCCESS: HasMoney -&amp;gt; DrinkSold
Customer grab a drink
SUCCESS: DrinkSold -&amp;gt; Idle
VendingMachine {currentState: Idle, stocks: 1}
-- Customer insert money and buy a drink --
SUCCESS: Idle -&amp;gt; HasMoney
SUCCESS: HasMoney -&amp;gt; DrinkSold
Customer grab a drink
SUCCESS: DrinkSold -&amp;gt; OutOfStock
VendingMachine {currentState: OutOfStock, stocks: 0}
-- Customer insert money --
ERROR: no state transition occurs
-- Owner is going to refill drinks --
SUCCESS: OutOfStock -&amp;gt; Idle
VendingMachine {currentState: Idle, stocks: 2}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Pitfalls
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;State pattern tends to end up having lots of classes because you'll have as many classes as states exist. If some states are almost identical, you could combine them together. This way, we reduce duplicate code but violate single responsibility principle, remember they are trade-off when you use State pattern.&lt;/li&gt;
&lt;li&gt;If there are many reachable states from one state, it will be more complicated to implement.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Comparison with Strategy Pattern
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;They both allows objects to incorporate different behavior through composition and delegation.&lt;/li&gt;
&lt;li&gt;In Strategy pattern, "Client" changes object's behavior at runtime. On the other hand, in State pattern, "Context" changes states according to well-defined state transition methods.&lt;/li&gt;
&lt;/ul&gt;




&lt;p&gt;You can check all the design pattern implementations here.&lt;br&gt;
&lt;a href="https://github.com/SotaNoniwa/DesignPattern2" rel="noopener noreferrer"&gt;GitHub Repository&lt;/a&gt;&lt;/p&gt;

</description>
      <category>computerscience</category>
      <category>java</category>
      <category>design</category>
      <category>designpatterns</category>
    </item>
    <item>
      <title>Composite Pattern</title>
      <dc:creator>Sota</dc:creator>
      <pubDate>Sat, 07 Dec 2024 10:19:10 +0000</pubDate>
      <link>https://dev.to/sota_333ad4b72095606ab40c/composite-pattern-4g84</link>
      <guid>https://dev.to/sota_333ad4b72095606ab40c/composite-pattern-4g84</guid>
      <description>&lt;h2&gt;
  
  
  What is Composite Pattern?
&lt;/h2&gt;

&lt;blockquote&gt;
&lt;p&gt;Composite pattern is a structural pattern that allows you to compose objects into tree structures to represent whole-part hierarchies. Composite lets clients treat individual objects and compositions of objects uniformly.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;In Composite pattern, elements with child elements are called &lt;strong&gt;nodes&lt;/strong&gt; and elements without children are called &lt;strong&gt;leaves&lt;/strong&gt;.&lt;/p&gt;

&lt;h2&gt;
  
  
  When to use it?
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;Use Composite pattern when you need whole-part or parent-child or tree-like hierarchy.&lt;/li&gt;
&lt;li&gt;Use Composite pattern when you want to let client to treat child and parent in a tree uniformly.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Problem
&lt;/h2&gt;

&lt;p&gt;We are trying to implement simple file system. First of all, we need &lt;code&gt;File&lt;/code&gt; and &lt;code&gt;Directory&lt;/code&gt; classes. But it will be difficult for client to keep checking which instances of classes each object is as our file structure grows bigger.&lt;br&gt;
File system is a perfect example of tree-like hierarchy, and we want to treat &lt;code&gt;File&lt;/code&gt; and &lt;code&gt;Directory&lt;/code&gt; uniformly. Time to use Composite pattern!&lt;/p&gt;
&lt;h2&gt;
  
  
  Solution
&lt;/h2&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fev464khuissdzkbkj3n2.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fev464khuissdzkbkj3n2.png" alt="Image description" width="631" height="401"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;Client&lt;br&gt;
Client doesn't care whether an object is instance of &lt;code&gt;File&lt;/code&gt; or &lt;code&gt;Directory&lt;/code&gt; thanks to &lt;code&gt;FileSystemComponent&lt;/code&gt;. Additionally, client doesn't have to write if statements to make sure whether he is calling right methods on the right objects.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;FileSystemComponent&lt;br&gt;
&lt;code&gt;File&lt;/code&gt; and &lt;code&gt;Directory&lt;/code&gt; are seen as &lt;code&gt;FileSystemComponent&lt;/code&gt; by Client. &lt;code&gt;FileSystemComponent&lt;/code&gt; defines default behavior for methods, default behavior can be exception, doing nothing, returning null or false, whatever makes sense for your application.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;File&lt;br&gt;
This is our leaf, overriding print method that prints its &lt;code&gt;name&lt;/code&gt; and &lt;code&gt;content&lt;/code&gt;.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Directory&lt;br&gt;
This is our node, overriding methods to add, remove, get children. &lt;code&gt;print&lt;/code&gt; method prints out its &lt;code&gt;name&lt;/code&gt; and calls children's &lt;code&gt;print&lt;/code&gt; methods as well so that Client doesn't need to call each component's &lt;code&gt;print&lt;/code&gt; method.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;
&lt;h2&gt;
  
  
  Structure
&lt;/h2&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fiu2388nh2oby8ugvnhd1.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fiu2388nh2oby8ugvnhd1.png" alt="Image description" width="721" height="611"&gt;&lt;/a&gt;&lt;/p&gt;
&lt;h2&gt;
  
  
  Implementation in Java
&lt;/h2&gt;


&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public abstract class FileSystemComponent {

    protected String name;

    public FileSystemComponent(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public void print(int indentLevel) {
        throw new UnsupportedOperationException();
    }

    public void add(FileSystemComponent component) {
        throw new UnsupportedOperationException();
    }

    public void remove(int index) {
        throw new UnsupportedOperationException();
    }

    // Instead of throwing exception, we do nothing by default.
    // Doing nothing makes sense because leaf has no child.
    public void getChildren() {
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public class File extends FileSystemComponent {

    private String content;

    public File(String name, String content) {
        super(name);
        this.content = content;
    }

    @Override
    public void print(int indentLevel) {
        String indent = " ".repeat(indentLevel);
        System.out.println(indent + name + ": " + content);
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public class Directory extends FileSystemComponent {

    private List&amp;lt;FileSystemComponent&amp;gt; children;

    public Directory(String name) {
        super(name);
        children = new ArrayList&amp;lt;&amp;gt;();
    }

    @Override
    public void print(int indentLevel) {
        String indent = " ".repeat(indentLevel);
        System.out.println(indent + name + " directory:");
        for (FileSystemComponent child : children) {
            child.print(indentLevel + 2);
        }
    }

    @Override
    public void add(FileSystemComponent component) {
        children.add(component);
    }

    @Override
    public void remove(int index) {
        children.remove(index);
    }

    @Override
    public void getChildren() {
        if (children.isEmpty()) {
            return;
        }
        StringBuilder builder = new StringBuilder("[");
        for (FileSystemComponent child : children) {
            builder.append(child.getName() + ", ");
        }
        builder.delete(builder.length() - 2, builder.length());
        builder.append("]");
        System.out.println(builder);
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public class FileSystemTestDrive {

    public static void main(String[] args) {
        FileSystemComponent rootDirectory = new Directory("Root");
        FileSystemComponent fruitsDirectory = new Directory("Fruits");
        FileSystemComponent animalDirectory = new Directory("Animal");
        FileSystemComponent felineDirectory = new Directory("Feline");

        rootDirectory.add(fruitsDirectory);
        rootDirectory.add(animalDirectory);

        fruitsDirectory.add(new File("Appple", "red and juicy."));
        fruitsDirectory.add(new File("Banana", "yellow and sweet."));
        fruitsDirectory.add(new File("Lemon", "yellow and sour."));

        animalDirectory.add(felineDirectory);
        felineDirectory.add(new File("Lion", "King of animal."));
        felineDirectory.add(new File("Tiger", "Has cool color pattern."));

        rootDirectory.print(0);
        rootDirectory.getChildren();
        rootDirectory.remove(0);
        rootDirectory.getChildren();

        // What happens we call getChildren() on leaf? (we don't override the method in leaf class)
        FileSystemComponent file = new File("sample", "this is leaf");
        file.getChildren(); // leaf calls default behavior, doing nothing
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;p&gt;Output:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Root directory:
  Fruits directory:
    Appple: red and juicy.
    Banana: yellow and sweet.
    Lemon: yellow and sour.
  Animal directory:
    Feline directory:
      Lion: King of animal.
      Tiger: Has cool color pattern.
[Fruits, Animal]
[Animal]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Pitfalls
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;If you want a composite that keeps its children in particular order, it requires more sophisticated management scheme for adding, removing and traversing children.&lt;/li&gt;
&lt;li&gt;As composite structure becomes larger and complex, it would be more expensive to traverse. In this case, you might consider to implement a cache that stores some data to save traversals.&lt;/li&gt;
&lt;/ul&gt;




&lt;p&gt;You can check all the design pattern implementations here.&lt;br&gt;
&lt;a href="https://github.com/SotaNoniwa/DesignPattern2" rel="noopener noreferrer"&gt;GitHub Repository&lt;/a&gt;&lt;/p&gt;

</description>
      <category>design</category>
      <category>designpatterns</category>
      <category>java</category>
      <category>computerscience</category>
    </item>
    <item>
      <title>Iterator Pattern</title>
      <dc:creator>Sota</dc:creator>
      <pubDate>Sat, 07 Dec 2024 01:21:01 +0000</pubDate>
      <link>https://dev.to/sota_333ad4b72095606ab40c/iterator-pattern-4ah1</link>
      <guid>https://dev.to/sota_333ad4b72095606ab40c/iterator-pattern-4ah1</guid>
      <description>&lt;h2&gt;
  
  
  What is Iterator Pattern?
&lt;/h2&gt;

&lt;blockquote&gt;
&lt;p&gt;Iterator pattern is a behavioral pattern that provides a way to access the elements of an aggregate (collection) object sequentially without exposing its underlying representation.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2&gt;
  
  
  When to use it?
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;Use Iterator pattern when you don't want to expose the data structure of your collection.&lt;/li&gt;
&lt;li&gt;User Iterator pattern when you want one common interface to traverse different data structures instead of having many similar traversal codes for each data structure in your app.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Problem
&lt;/h2&gt;

&lt;p&gt;Company "Alpha Inc." is going to merge with "Beta Inc.". We are in HR department and have to merge their employees data together.&lt;br&gt;
&lt;code&gt;EmployeeListA&lt;/code&gt; holds Alpha employees' data, and &lt;code&gt;EmployeeListB&lt;/code&gt; has Beta employees' data. Because &lt;code&gt;EmployeeListA&lt;/code&gt; uses Array data structure and &lt;code&gt;EmployeeListB&lt;/code&gt; uses ArrayList, we write two traversal codes.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fp3r464xrl99s3h0g8wqc.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fp3r464xrl99s3h0g8wqc.png" alt="Image description" width="541" height="321"&gt;&lt;/a&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public class HRDepartment {

    public void printEmployee(){
        EmployeeListA employeeListA = new EmployeeListA("Alpha Inc");
        String[] alphaEmployee = employeeListA.getEmployees();

        EmployeeListB employeeListB = new EmployeeListB("Beta Inc");
        List&amp;lt;String&amp;gt; betaEmployee = employeeListB.getEmployees();

        // Traversal code for Array
        for (int i = 0; i &amp;lt; alphaEmployee.length; i++) {
            System.out.println(alphaEmployee[i] + " from Alpha Inc.");
        }

        // Traversal code for ArrayList
        for (int i = 0; i &amp;lt; betaEmployee.size(); i++) {
            System.out.println(betaEmployee.get(i) + " from Beta Inc.");
        }
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Can you spot the problems? Here's the issue our code currently has:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;We are coding to concrete implementation (&lt;code&gt;EmployeeListA&lt;/code&gt; and &lt;code&gt;EmployeeListB&lt;/code&gt;) not to an interface.&lt;/li&gt;
&lt;li&gt;If we decide to switch &lt;code&gt;EmployeeListA&lt;/code&gt; data structure from Array to another one such as hash map, we need to modify our &lt;code&gt;HRDepartment&lt;/code&gt; class a lot.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;HRDepartment&lt;/code&gt; needs to know aggregate's internal structure, in other words, we are exposing our collection's data structure.&lt;/li&gt;
&lt;li&gt;We have duplication of traversal code for different data structure, Array and ArrayList.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Solution
&lt;/h2&gt;

&lt;h3&gt;
  
  
  Encapsulate iteration logic
&lt;/h3&gt;

&lt;p&gt;So where to begin? Let's remove our duplicate iteration codes.&lt;br&gt;
It would be great if we can encapsulate iteration logic and introduce a common interface so that &lt;code&gt;HRDepartment&lt;/code&gt; can use just one interface to iterate any data structure.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fm2alotvlhepur7dhrvhs.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fm2alotvlhepur7dhrvhs.png" alt="Image description" width="800" height="375"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;We need &lt;code&gt;Iterator&lt;/code&gt; interface to decouple iteration logic from &lt;code&gt;HRDepartment&lt;/code&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public interface Iterator {
    boolean hasNext();
    String next();
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;hasNext()&lt;/code&gt; returns boolean value indicating whether a collection has next element or not. &lt;code&gt;next()&lt;/code&gt; returns next element in a collection. (you will see actual implementation later)&lt;/p&gt;

&lt;p&gt;In &lt;code&gt;EmployeeListA&lt;/code&gt;/&lt;code&gt;EmployeeListA&lt;/code&gt;, We removed &lt;code&gt;getEmployees()&lt;/code&gt; method because it exposes our aggregate's data structure. And importantly, we wrote new method &lt;code&gt;createIterator()&lt;/code&gt; which creates an corresponding concrete Iterator, for example, &lt;code&gt;EmployeeListA.createIterator()&lt;/code&gt; instantiates &lt;code&gt;EmployeeListAIterator&lt;/code&gt;.&lt;/p&gt;

&lt;h3&gt;
  
  
  Introduce common interface for aggregates
&lt;/h3&gt;

&lt;p&gt;Okay, we now encapsulated Iteration logic, our aggregates do not expose their underlying representation, removed duplicate traversal codes. But still one problem remains, &lt;code&gt;HRDepartment&lt;/code&gt; depends on concrete aggregates. Let's introduce a common interface for concrete aggregates.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fb18wtqdnj1fu3kz2c3dg.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fb18wtqdnj1fu3kz2c3dg.png" alt="Image description" width="800" height="232"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Structure
&lt;/h2&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fck5ocvn63nnxcpcz58j9.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fck5ocvn63nnxcpcz58j9.png" alt="Image description" width="791" height="571"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Implementation in Java
&lt;/h2&gt;

&lt;p&gt;I'll omit &lt;code&gt;EmployeeListBIterator&lt;/code&gt; and &lt;code&gt;EmployeeListB&lt;/code&gt;'s implementation as they are similar to those of &lt;code&gt;EmployeeListAIterator&lt;/code&gt; and &lt;code&gt;EmployeeListA&lt;/code&gt;. If you're not sure how to implement them, you can check in my GitHub repo (link to my repo is at the end of this blog).&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public interface Iterator {
    boolean hasNext();
    String next();
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public class EmployeeListAIterator implements Iterator {

    private String[] employees;
    private int index = 0;

    public EmployeeListAIterator(String[] employees) {
        this.employees = employees;
    }

    @Override
    public boolean hasNext() {
        if (index &amp;gt;= employees.length || employees[index] == null) {
            return false;
        }
        return true;
    }

    @Override
    public String next() {
        String employee = employees[index];
        index++;
        return employee;
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public interface EmployeeList {
    Iterator createIterator();
    String getCompanyName();
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public class EmployeeListA implements EmployeeList{

    private String companyName;
    private String[] employees;
    private int SIZE = 5;
    private int index = 0;

    public EmployeeListA(String companyName) {
        this.companyName = companyName;
        employees = new String[SIZE];
        addEmployee("Alice");
        addEmployee("Alisha");
        addEmployee("Alex");
    }

    public void addEmployee(String name) {
        employees[index] = name;
        index++;
    }

    public Iterator createIterator() {
        return new EmployeeListAIterator(employees);
    }

    public String getCompanyName() {
        return companyName;
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public class HRDepartment {

    EmployeeList listA;
    EmployeeList listB;

    public HRDepartment(EmployeeList listA, EmployeeList listB) {
        this.listA = listA;
        this.listB = listB;
    }

    public void printEmployee() {
        Iterator listAIterator = listA.createIterator();
        Iterator listBIterator = listB.createIterator();

        System.out.println("--- Employees from " + listA.getCompanyName() + " ---");
        printEmployee(listAIterator);
        System.out.println("--- Employees from " + listB.getCompanyName() + " ---");
        printEmployee(listBIterator);
    }

    private void printEmployee(Iterator iterator) {
        while (iterator.hasNext()) {
            System.out.println(iterator.next());
        }
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Output:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;--- Employees from Alpha Inc ---
Alice
Alisha
Alex
--- Employees from Beta Inc ---
Bob
Bella
Benjamin
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Pitfalls
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;Iterator itself imply no ordering in which elements are visited during iteration. The order of iteration depends on the underlying data structure being traversed, not on the Iterator.&lt;/li&gt;
&lt;li&gt;Iterator does not support accessing elements by index.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Iterator &amp;amp; Iterable interface in Java
&lt;/h2&gt;

&lt;p&gt;Before the end of this blog, let's check how we can use &lt;code&gt;java.util.Iterator&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fflm7ttt1kqe318s7snsr.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fflm7ttt1kqe318s7snsr.png" alt="Image description" width="561" height="501"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;All Collection classes such as ArrayList, implement the Collection interface, which extends Iterable interface. Thus every Collection class is Iterable.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public class IteratorDemo {
    public static void main(String[] args) {
        List&amp;lt;Integer&amp;gt; nums = new ArrayList&amp;lt;&amp;gt;(List.of(0, 1, 2, 3));
        Iterator&amp;lt;Integer&amp;gt; iterator = nums.iterator();
        while (iterator.hasNext()) {
            System.out.println(iterator.next());
        }
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;






&lt;p&gt;You can check all the design pattern implementations here.&lt;br&gt;
&lt;a href="https://github.com/SotaNoniwa/DesignPattern2" rel="noopener noreferrer"&gt;GitHub Repository&lt;/a&gt;&lt;/p&gt;

</description>
      <category>java</category>
      <category>computerscience</category>
      <category>design</category>
      <category>designpatterns</category>
    </item>
    <item>
      <title>Template Method Pattern</title>
      <dc:creator>Sota</dc:creator>
      <pubDate>Thu, 05 Dec 2024 07:40:41 +0000</pubDate>
      <link>https://dev.to/sota_333ad4b72095606ab40c/template-method-pattern-1i91</link>
      <guid>https://dev.to/sota_333ad4b72095606ab40c/template-method-pattern-1i91</guid>
      <description>&lt;h2&gt;
  
  
  What is Template method pattern?
&lt;/h2&gt;

&lt;blockquote&gt;
&lt;p&gt;Template method pattern defines the skeleton of an algorithm in a method, deferring some steps to subclasses. Template method lets subclasses redefine certain steps of an algorithm without changing the algorithm's structure.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2&gt;
  
  
  When to use it?
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;Use Template method pattern when you have classes that contains similar algorithms with minor differences.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Problem
&lt;/h2&gt;

&lt;p&gt;Let's say we create classes represents animal behavior. Our first version of implementation is below:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fc4hk73wj9gyxxzxmj6rs.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fc4hk73wj9gyxxzxmj6rs.png" alt="Image description" width="511" height="411"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Dog and Bird, they both wake up in the morning and sleep in the night, but eat different things. Our superclass Animal defines common methods for all animals such as &lt;code&gt;wakeUp()&lt;/code&gt; and &lt;code&gt;sleep()&lt;/code&gt;, but &lt;code&gt;doDailyRoutine()&lt;/code&gt; method is declared as abstract and we delegate its implementation to subclasses because it is vary for each animal.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public abstract class Animal {

    public String name;

    public Animal(String name) {
        this.name = name;
    }

    public abstract void doDailyRoutine();

    public void wakeUp() {
        System.out.println(name + " wakes up in the morning.");
    }

    public void sleep() {
        System.out.println(name + " sleeps in the night.");
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public class Bird extends Animal {

    public Bird(String name) {
        super(name);
    }

    @Override
    public void doDailyRoutine() {
        wakeUp();
        eatFruit();
        sleep();
    }

    public void eatFruit() {
        System.out.println(name + " eats a fruit.");
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public class Dog extends Animal {

    public Dog(String name) {
        super(name);
    }

    @Override
    public void doDailyRoutine() {
        wakeUp();
        eatDogFood();
        sleep();
    }

    public void eatDogFood() {
        System.out.println(name + " eats dog food.");
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The problem we have is &lt;code&gt;eatFruit&lt;/code&gt; and &lt;code&gt;eatDogFood&lt;/code&gt; methods. Despite of different kinds of foods, they both do the same thing, eating. For just one slight difference, we need to write &lt;code&gt;doDailyRoutine&lt;/code&gt; method in subclasses over and over. So we should pull up abstraction level to get rid of code duplication.&lt;br&gt;
Also, animals may have their own behavior. We'll see how we can make a room for additional behavior, yet still reduces code duplication.&lt;/p&gt;
&lt;h2&gt;
  
  
  Solution
&lt;/h2&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fpjvo5d87sr1t1ge57l9n.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fpjvo5d87sr1t1ge57l9n.png" alt="Image description" width="731" height="411"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;Animal&lt;br&gt;
Instead of defining &lt;code&gt;doDailyRoutine&lt;/code&gt; in subclasses, we define it in superclass &lt;code&gt;Animal&lt;/code&gt;. All animals exactly follow the order, that is, &lt;code&gt;wakeUp&lt;/code&gt;, &lt;code&gt;eat&lt;/code&gt;, &lt;code&gt;sleep&lt;/code&gt;. &lt;code&gt;eat&lt;/code&gt; method is declared as abstract because each animal eats different things. &lt;br&gt;
&lt;code&gt;additionalBehavior&lt;/code&gt; has empty body, so it does nothing. However, we can override the method in subclasses if some animal have unique behavior. This kind of method is called &lt;strong&gt;hook&lt;/strong&gt; in Template method pattern.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Animal subclasses&lt;br&gt;
Although animal subclasses can't change algorithm structure, they can override some of the step methods used by &lt;code&gt;doDailyRoutine()&lt;/code&gt;. Also, they can optionally add additional behavior by overriding the hook method.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;
&lt;h2&gt;
  
  
  Structure
&lt;/h2&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fvhih06uyphdyldxmg0rv.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fvhih06uyphdyldxmg0rv.png" alt="Image description" width="492" height="282"&gt;&lt;/a&gt;&lt;/p&gt;
&lt;h2&gt;
  
  
  Implementation in Java
&lt;/h2&gt;


&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public abstract class Animal {

    public String name;

    public Animal(String name) {
        this.name = name;
    }

    // TemplateMethod is final to prevent subclasses changes its structure
    public final void doDailyRoutine() {
        wakeUp();
        additionalBehavior();
        eat();
        sleep();
    }

    public void wakeUp() {
        System.out.println(name + " wakes up in the morning.");
    }

    public abstract void eat();

    public void sleep() {
        System.out.println(name + " sleeps in the night.");
    }

    public void additionalBehavior() {
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public class Dog extends Animal {

    public Dog(String name) {
        super(name);
    }

    @Override
    public void eat() {
        System.out.println(name + " eats dog food.");
    }

    @Override
    public void additionalBehavior() {
        System.out.println(name + " gets cuddled.");
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public class Bat extends Animal {

    public Bat(String name) {
        super(name);
    }

    @Override
    public void wakeUp() {
        System.out.println(name + " wakes up in the night.");
    }

    @Override
    public void eat() {
        System.out.println(name + " eats insects.");
    }

    @Override
    public void sleep() {
        System.out.println(name + " sleeps in the morning.");
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public class AnimalTestDrive {

    public static void main(String[] args) {
        Animal bird = new Bird("Pigeon");
        Animal dog = new Dog("Golden retriever");
        Animal bat = new Bat("Silver-haired bat");

        bird.doDailyRoutine();
        System.out.println();
        dog.doDailyRoutine();
        System.out.println();
        bat.doDailyRoutine();
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;p&gt;Output:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Pigeon wakes up in the morning.
Pigeon sings.
Pigeon eats fruits.
Pigeon sleeps in the night.

Golden retriever wakes up in the morning.
Golden retriever gets cuddled.
Golden retriever eats dog food.
Golden retriever sleeps in the night.

Silver-haired bat wakes up in the night.
Silver-haired bat eats insects.
Silver-haired bat sleeps in the morning.
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Pitfalls
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;Algorithm implementations can be spread over multiple subclasses making it hard to maintain.&lt;/li&gt;
&lt;li&gt;Granularity and flexibility are tradeoff relationship. If AbstractClass have many abstract methods, it offers more flexibility but we'll have more burden in subclasses. &lt;/li&gt;
&lt;/ul&gt;




&lt;p&gt;You can check all the design pattern implementations here.&lt;br&gt;
&lt;a href="https://github.com/SotaNoniwa/DesignPattern2" rel="noopener noreferrer"&gt;GitHub Repository&lt;/a&gt;&lt;/p&gt;

</description>
      <category>java</category>
      <category>computerscience</category>
      <category>design</category>
      <category>designpatterns</category>
    </item>
    <item>
      <title>Facade Pattern</title>
      <dc:creator>Sota</dc:creator>
      <pubDate>Tue, 03 Dec 2024 00:39:55 +0000</pubDate>
      <link>https://dev.to/sota_333ad4b72095606ab40c/facade-pattern-1efk</link>
      <guid>https://dev.to/sota_333ad4b72095606ab40c/facade-pattern-1efk</guid>
      <description>&lt;h2&gt;
  
  
  What is Facade Pattern?
&lt;/h2&gt;

&lt;blockquote&gt;
&lt;p&gt;Facade pattern is a structural pattern that provides a unified interface to a set of interfaces in a subsystem. Facade defines a higher-level interface that makes the subsystem easier to use.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2&gt;
  
  
  When to use it?
&lt;/h2&gt;

&lt;p&gt;Use Facade pattern when you need simplified interface that orchestrates many classes and does the complex work.&lt;/p&gt;

&lt;h2&gt;
  
  
  Problem
&lt;/h2&gt;

&lt;p&gt;Our company is going to sell a car. To start driving, a client needs to follow these procedure...&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;unlock the door&lt;/li&gt;
&lt;li&gt;open the door&lt;/li&gt;
&lt;li&gt;start engine&lt;/li&gt;
&lt;li&gt;turn on the dashboard&lt;/li&gt;
&lt;li&gt;turn on the navigation screen&lt;/li&gt;
&lt;li&gt;if outside is dark, turn on the headlight&lt;/li&gt;
&lt;li&gt;close the door &lt;/li&gt;
&lt;li&gt;lock the door&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Even a client hasn't pedal yet, there are already 8 steps.&lt;br&gt;
How would it be in OOP? In fact, we need 5 different classes and 8 methods calls.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;        door.unlock();
        door.open();
        engine.start();
        dashBoard.on();
        screen.on();
        if (isOutsideDark) {
            light.on();
        }
        door.close();
        door.lock();
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The question is, is there a easier way for a client to deal with tasks such as starting driving, stopping driving and so on? Yes, there is Facade pattern.&lt;/p&gt;

&lt;h2&gt;
  
  
  Solution
&lt;/h2&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fw436hfcxrkzs9554juiw.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fw436hfcxrkzs9554juiw.png" alt="Image description" width="721" height="721"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;Client&lt;br&gt;
Client can use CarFacade to do a task, and have access to subsystem classes.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;CarFacade&lt;br&gt;
Provides simplified interface to start driving, stop driving.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Subsystem classes&lt;br&gt;
Complex system that hard to use. (For the sake of simplicity, I implemented not much complex subsystem)&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  Structure
&lt;/h2&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fn3ezruympyvur1ii2t4g.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fn3ezruympyvur1ii2t4g.png" alt="Image description" width="781" height="631"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Implementation in Java
&lt;/h2&gt;

&lt;p&gt;Implementing subsystem classes is not important to explain Facade pattern, so I omit these parts but you can check in my Github at the end of this blog.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public class CarFacade {

    private DashBoard dashBoard;
    private Door door;
    private Engine engine;
    private HeadLight light;
    private NavigationScreen screen;

    private boolean isOutsideDark;

    public CarFacade(DashBoard dashBoard,
                     Door door,
                     Engine engine,
                     HeadLight light,
                     NavigationScreen screen,
                     boolean isOutsideDark) {
        this.dashBoard = dashBoard;
        this.door = door;
        this.engine = engine;
        this.light = light;
        this.screen = screen;
        this.isOutsideDark = isOutsideDark;
    }

    public void startDriving() {
        door.unlock();
        door.open();
        engine.start();
        dashBoard.on();
        screen.on();
        if (isOutsideDark) {
            light.on();
        }
        door.close();
        door.lock();
    }

    public void endDriving() {
        light.off();
        screen.off();
        dashBoard.off();
        engine.stop();
        door.unlock();
        door.open();
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public class Client {

    public static void main(String[] args) {
        // Create components
        DashBoard dashBoard = new DashBoard();
        Door door = new Door();
        Engine engine = new Engine();
        HeadLight light = new HeadLight();
        GPS gps = new GPS();
        NavigationScreen screen = new NavigationScreen(gps);

        // Instantiates Facade with all the components in the subsystem
        CarFacade automatedCar = new CarFacade(dashBoard, door, engine, light, screen, true);

        // Use the simplified interface to start and end driving
        automatedCar.startDriving();
        System.out.println();
        automatedCar.endDriving();
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Output:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Unlock the door
Open the door
Start Engine
DashBoard displays speed: 60km/h, fuel remaining: 70%
Navigation screen displays gps: 43.01787, -76.216435
HeadLight is on
Close the door
Lock the door

HeadLight is off
Navigation screen is off
DashBoard is off
Stop Engine
Unlock the door
Open the door
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Pitfalls
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;There is no really known pitfall to Facade.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Comparison with Adapter Pattern
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;Adapter pattern introduces new interface to adapt incompatible interface to the interface the client expects, while Facade pattern creates unified interface that makes subsystem easier to use.&lt;/li&gt;
&lt;/ul&gt;




&lt;p&gt;You can check all the design pattern implementations here.&lt;br&gt;
&lt;a href="https://github.com/SotaNoniwa/DesignPattern2" rel="noopener noreferrer"&gt;GitHub Repository&lt;/a&gt;&lt;/p&gt;

</description>
      <category>computerscience</category>
      <category>java</category>
      <category>design</category>
      <category>designpatterns</category>
    </item>
    <item>
      <title>Adapter Pattern</title>
      <dc:creator>Sota</dc:creator>
      <pubDate>Sat, 30 Nov 2024 06:45:13 +0000</pubDate>
      <link>https://dev.to/sota_333ad4b72095606ab40c/adapter-pattern-bdf</link>
      <guid>https://dev.to/sota_333ad4b72095606ab40c/adapter-pattern-bdf</guid>
      <description>&lt;h2&gt;
  
  
  What is Adapter Pattern?
&lt;/h2&gt;

&lt;blockquote&gt;
&lt;p&gt;Adapter pattern is a structural pattern that converts the interface of a class into another interface the clients expect. Adapter lets classes work together that couldn't otherwise because of incompatible interfaces.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2&gt;
  
  
  When to use it?
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;Use Adapter pattern when you want to use legacy code or third-party libraries but its interface is incompatible with other part of your application.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Problem
&lt;/h2&gt;

&lt;p&gt;We've been using an old printer but now new free software is invented which is integrated with modern printer. The problem is we can't afford to buy modern printer but still want to use the software. Is there a way of using new software but with old printer which is incompatible with the software? Yes, here Adapter pattern comes in handy.&lt;/p&gt;

&lt;h2&gt;
  
  
  Solution
&lt;/h2&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fkfzxzg1pp36wlkf1xjwk.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fkfzxzg1pp36wlkf1xjwk.png" alt="Image description" width="611" height="271"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;NewSoftware&lt;br&gt;
This is our Client. This only accepts &lt;code&gt;ModernPrinter&lt;/code&gt; interface. NewSoftware thinks it's dealing with &lt;code&gt;ModernPrinter&lt;/code&gt;.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;ModernPrinter&lt;br&gt;
Provides compatible interface for Client.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;PrinterAdapter&lt;br&gt;
Receives a method call &lt;code&gt;modernPrint()&lt;/code&gt; from &lt;code&gt;ModernPrinter&lt;/code&gt;, then translates it into a format the &lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;OldPrinter&lt;br&gt;
This is what we want to use but its interface is incompatible with our &lt;code&gt;NewSoftware&lt;/code&gt;. &lt;code&gt;oldPrint()&lt;/code&gt; gets executed when &lt;code&gt;ModernPrinter&lt;/code&gt; calls &lt;code&gt;modernPrint()&lt;/code&gt;.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  Structure
&lt;/h2&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Ff5qr2a6ref2jdrmm9e7h.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Ff5qr2a6ref2jdrmm9e7h.png" alt="Image description" width="800" height="429"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Remember an adapter can be used with any subclass of the adaptee.&lt;/p&gt;

&lt;h2&gt;
  
  
  Implementation in Java
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public class OldPrinter {

    public void oldPrint(String document) {
        System.out.println(document + " by old printer");
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public interface ModernPrinter {

    void modernPrint(String document);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public class PrinterAdapter implements ModernPrinter {

    private OldPrinter oldPrinter;

    public PrinterAdapter(OldPrinter oldPrinter) {
        this.oldPrinter = oldPrinter;
    }

    @Override
    public void modernPrint(String document) {
        oldPrinter.oldPrint(document);
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public class NewSoftware {

    public static void main(String[] args) {
        OldPrinter oldPrinter = new OldPrinter();
        // Because PrinterAdapter implements ModernPrinter, it can be seen
        // as a ModernPrinter which is integrated with NewSoftware
        ModernPrinter adapter = new PrinterAdapter(oldPrinter);
        adapter.modernPrint("Hello world");
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In our assumption, you &lt;code&gt;NewSoftware&lt;/code&gt; is integrated with &lt;code&gt;ModernPrinter&lt;/code&gt;, so it doesn't make sense to code like &lt;code&gt;oldPrinter.oldPrint("Hello world");&lt;/code&gt; in &lt;code&gt;NewSoftware&lt;/code&gt; class (even though it will be compiled without errors).&lt;/p&gt;

&lt;p&gt;Output:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Hello world by old printer
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Object and Class Adapter
&lt;/h2&gt;

&lt;p&gt;What we’ve seen is called an &lt;strong&gt;Object Adapter&lt;/strong&gt;, which adapts the adaptee using composition. There is another type of adapter called a &lt;strong&gt;Class Adapter&lt;/strong&gt;, which uses inheritance to achieve the intent of the Adapter pattern.&lt;/p&gt;

&lt;p&gt;Java doesn't support multiple inheritance. So we can't use class adapter in Java, but we will study it anyway as you might encounter class adapter in other language.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fae535uc6h1fs9psdz6kv.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fae535uc6h1fs9psdz6kv.png" alt="Image description" width="591" height="281"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Because object adapter uses composition, &lt;code&gt;Adapter&lt;/code&gt; can hold references to one or more &lt;code&gt;Adaptee&lt;/code&gt; objects. Thus, object adapter offers more flexibility. While class adapter is tightly coupled with one and only one adaptee which leads to less flexibility.&lt;/p&gt;

&lt;h2&gt;
  
  
  Pitfalls
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;An adapter that does a lot of work besides simple interface translation results in adding/altering adaptee behavior, which is far from the intent of Adapter pattern.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Comparison with Decorator Pattern
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;Decorator pattern wraps object to add small behavior, while Adapter pattern wraps object to adapt to the interface that is required by Client.&lt;/li&gt;
&lt;/ul&gt;




&lt;p&gt;You can check all the design pattern implementations here.&lt;br&gt;
&lt;a href="https://github.com/SotaNoniwa/DesignPattern2" rel="noopener noreferrer"&gt;GitHub Repository&lt;/a&gt;&lt;/p&gt;

</description>
      <category>computerscience</category>
      <category>java</category>
      <category>design</category>
      <category>designpatterns</category>
    </item>
    <item>
      <title>Command Pattern</title>
      <dc:creator>Sota</dc:creator>
      <pubDate>Thu, 28 Nov 2024 23:57:24 +0000</pubDate>
      <link>https://dev.to/sota_333ad4b72095606ab40c/command-pattern-4m05</link>
      <guid>https://dev.to/sota_333ad4b72095606ab40c/command-pattern-4m05</guid>
      <description>&lt;h2&gt;
  
  
  What is Command Pattern?
&lt;/h2&gt;

&lt;blockquote&gt;
&lt;p&gt;Command pattern is a behavioral pattern that encapsulates a request as an independent object, thereby letting you pass requests as method arguments, queue or log requests, and support undoable operation.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2&gt;
  
  
  When to use it?
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;Use Command pattern when you need to decouple an object making requests from the objects that know how to perform the requests.&lt;/li&gt;
&lt;li&gt;Use Command pattern when you want to inject or assign different requests to objects at runtime.&lt;/li&gt;
&lt;li&gt;Use Command pattern when you need undo or redo operation in your application.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Problem
&lt;/h2&gt;

&lt;p&gt;Imagine we are designing API for a remote control that manipulates electronic devices in client house. Here we have lots of vender classes.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fnxmt874pwllltrp0g6yh.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fnxmt874pwllltrp0g6yh.png" alt="Image description" width="641" height="341"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Introducing a common interface doesn't seem to be interesting since our vender classes are diverse, and it is also expected that we will have more vender classes.&lt;/p&gt;

&lt;p&gt;Additionally, the remote control shouldn't consist of a set of if statements such as &lt;code&gt;if slot1 == light, then light.turnOn(), else if slot1 == tv, then tv.turnOn()&lt;/code&gt; because it is a bad design.&lt;/p&gt;

&lt;h2&gt;
  
  
  Solution
&lt;/h2&gt;

&lt;p&gt;Simply put, we want the remote control to know how to make a generic request but not to care about a specific vender class. To achieve this, we are going to separate our concern into two classes, one makes a request and another one actually performs the work to comply the request.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Frp9c5mkm9cljbofi7s34.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Frp9c5mkm9cljbofi7s34.png" alt="Image description" width="800" height="391"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;RemoteControl&lt;br&gt;
This is the one that makes a request such as &lt;code&gt;command.execute()&lt;/code&gt;, but doesn't care how to perform the work.&lt;br&gt;
If you want &lt;code&gt;RemoteControl&lt;/code&gt; to have multiple slots—for example, one for &lt;code&gt;OutdoorLight&lt;/code&gt; and another for &lt;code&gt;TV&lt;/code&gt;—&lt;code&gt;RemoteControl&lt;/code&gt; can have arrays of commands, such as &lt;code&gt;onCommands[]&lt;/code&gt; and &lt;code&gt;offCommands[]&lt;/code&gt;. The &lt;code&gt;setCommand&lt;/code&gt; method can take an integer to determine which slot to set. For instance, &lt;code&gt;setCommand(2, TVonCommand, TVoffCommand)&lt;/code&gt; might assign &lt;code&gt;TVonCommand&lt;/code&gt; to &lt;code&gt;onCommands[2]&lt;/code&gt; and &lt;code&gt;TVoffCommand&lt;/code&gt; to &lt;code&gt;offCommands[2]&lt;/code&gt;.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Command&lt;br&gt;
Provides interface for all the ConcreteCommands.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;ConcreteCommand&lt;br&gt;
TurnOnOutdoorLightCommand object calls execute() method and delegates "how to turn on light" to the holding OurdoorLight object.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;OutdoorLight&lt;br&gt;
This is the one that knows how to perform the work to comply the request from RemoteControl.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Client&lt;br&gt;
Client is responsible for creating ConcreteCommands and associates them with the corresponding Receivers.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  Structure
&lt;/h2&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fvik2c6pd59ffl7h39hn7.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fvik2c6pd59ffl7h39hn7.png" alt="Image description" width="800" height="502"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Implementation in Java
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Receiver
public class OutdoorLight {

    public void turnOn() {
        System.out.println("Outdoor light is on");
    }

    public void turnOff() {
        System.out.println("Outdoor light is off");
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public interface Command {

    void execute();

    void undo();
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Concrete command
public class TurnOnOutdoorCommand implements Command {

    private OutdoorLight outdoorLight;

    public TurnOnOutdoorCommand(OutdoorLight outdoorLight) {
        this.outdoorLight = outdoorLight;
    }

    @Override
    public void execute() {
        outdoorLight.turnOn();
    }

    @Override
    public void undo() {
        outdoorLight.turnOff();
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Concrete command
public class TurnOffOutdoorLightCommand implements Command {

    OutdoorLight outdoorLight;

    public TurnOffOutdoorLightCommand(OutdoorLight outdoorLight) {
        this.outdoorLight = outdoorLight;
    }

    @Override
    public void execute() {
        outdoorLight.turnOff();
    }

    @Override
    public void undo() {
        outdoorLight.turnOn();
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Null Object
public class NoCommand implements Command {

    @Override
    public void execute() {
    }

    @Override
    public void undo() {
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Invoker
public class RemoteControl {

    private Command onCommand;
    private Command offCommand;
    public Stack&amp;lt;Command&amp;gt; undoCommands;

    public RemoteControl() {
        onCommand = new NoCommand();
        offCommand = new NoCommand();
        undoCommands = new Stack&amp;lt;&amp;gt;();
        undoCommands.push(new NoCommand());
    }

    public void setCommand(Command onCommand, Command offCommand) {
        this.onCommand = onCommand;
        this.offCommand = offCommand;
    }

    public void onButtonWasPushed() {
        onCommand.execute();
        undoCommands.push(onCommand);
    }

    public void offButtonWasPushed() {
        offCommand.execute();
        undoCommands.push(offCommand);
    }

    public void undoButtonWasPushed() {
        if (!(undoCommands.peek() instanceof NoCommand)) {
            Command lastCommand = undoCommands.pop();
            lastCommand.undo();
        } else {
            System.out.println("undoCommands stack is empty!");
        }
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public class Client {

    public static void main(String[] args) {
        OutdoorLight outdoorLight = new OutdoorLight(); // Create a receiver

        // Create commands on that receiver
        // These commands are encapsulated requests in other words
        Command turnOnOutdoorLight = new TurnOnOutdoorCommand(outdoorLight);
        Command turnOffOutdoorLight = new TurnOffOutdoorLightCommand(outdoorLight);

        RemoteControl rc = new RemoteControl(); // Create an invoker
        // We can pass encapsulated requests to other object
        rc.setCommand(turnOnOutdoorLight, turnOffOutdoorLight); // Set command on that invoker

        rc.undoButtonWasPushed();
        rc.onButtonWasPushed();
        rc.offButtonWasPushed();
        rc.undoButtonWasPushed();
        rc.undoButtonWasPushed();
        rc.undoButtonWasPushed();
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Output:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;undoCommands stack is empty!
Outdoor light is on
Outdoor light is off
Outdoor light is on
Outdoor light is off
undoCommands stack is empty!
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;NoCommand&lt;/code&gt; is know as &lt;strong&gt;Null Object&lt;/strong&gt; which is another design pattern. It is useful when you don't have a meaning object to return. Here we use it as default command that &lt;code&gt;Invoker&lt;/code&gt; holds so that we don't need to handle null.&lt;/p&gt;

&lt;h2&gt;
  
  
  Pitfalls
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;Client needs to do lots of things such as creating &lt;code&gt;ConcreteCommands&lt;/code&gt; &amp;amp; setting corresponding &lt;code&gt;Receivers&lt;/code&gt;, creating &lt;code&gt;Invoker&lt;/code&gt; &amp;amp; setting &lt;code&gt;ConcreteCommands&lt;/code&gt; on that &lt;code&gt;Invoker&lt;/code&gt;.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  MacroCommand
&lt;/h2&gt;

&lt;p&gt;MacroCommand is a simple extension of Command pattern that allows you to have one command that turns on a light, TV, AC, coffee machine and plays music.&lt;br&gt;
Let's make a new kind of Command that executes a set of other Commands.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public class MacroCommand implements Command {

    Command[] commands;

    public MacroCommand(Command[] commands) {
        this.commands = commands;
    }

    // Executes holding commands one at a time
    @Override
    public void execute() {
        for (Command command : commands) {
            command.execute();
        }
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;That's it! Now we're ready to use our MacroCommand. But before that, let me show you how to implement RemoteControl that can have multiple slots as I mentioned in "Solution" section.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public class RemoteControl {

    private Command[] onCommands;
    private Command[] offCommands;

    public RemoteControl() {
        // Our RemoteControl has 3 slots
        onCommands = new Command[3];
        offCommands = new Command[3];

        Command noCommand = new NoCommand();
        for (int i = 0; i &amp;lt; onCommands.length; i++) {
            onCommands[i] = noCommand;
            offCommands[i] = noCommand;
        }
    }

    public void setCommands(int slot, Command onCommand, Command offCommand) {
        onCommands[slot] = onCommand;
        offCommands[slot] = offCommand;
    }

    public void onButtonWasPushed(int slot) {
        onCommands[slot].execute();
    }

    public void offButtonWasPushed(int slot) {
        offCommands[slot].execute();
    }

    // Print slots info in pretty style
    @Override
    public String toString() {
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("\n------ Remote Control ------\n");
        for (int i = 0; i &amp;lt; onCommands.length; i++) {
            stringBuilder.append("[slot " + i + "] " + onCommands[i].getClass().getSimpleName() +
                    "    " + offCommands[i].getClass().getSimpleName() + "\n");
        }
        return stringBuilder.toString();
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Pretty simple, just use array to store multiple commands.&lt;br&gt;
Finally, Client uses our MacroCommand. For the sake of simplicity, I created only two receivers, &lt;code&gt;Light&lt;/code&gt; and &lt;code&gt;CoffeeMachine&lt;/code&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public class Client {

    public static void main(String[] args) {
        // Create receivers
        Light light = new Light();
        CoffeeMachine coffeeMachine = new CoffeeMachine();

        // Create commands and set corresponding receivers on them
        Command lightOnCommand = new LightOnCommand(light);
        Command lightOffCommand = new LightOffCommand(light);
        Command coffeeMachineOnCommand = new CoffeeMachineOn(coffeeMachine);
        Command coffeeMachineOffCommand = new CoffeeMachineOff(coffeeMachine);

        // Create arrays of commands
        Command[] morningOn = {lightOnCommand, coffeeMachineOnCommand};
        Command[] morningOff = {lightOffCommand, coffeeMachineOffCommand};

        // Create macros
        MacroCommand morningOnMacro = new MacroCommand(morningOn);
        MacroCommand morningOffMacro = new MacroCommand(morningOff);

        RemoteControl rc = new RemoteControl();
        rc.setCommands(0, morningOnMacro, morningOffMacro);

        System.out.println(rc);

        System.out.println("--- Pushing Macro On ---");
        rc.onButtonWasPushed(0);
        System.out.println("\n--- Pushing Macro Off ---");
        rc.offButtonWasPushed(0);
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Output:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;------ Remote Control ------
[slot 0] MacroCommand    MacroCommand
[slot 1] NoCommand    NoCommand
[slot 2] NoCommand    NoCommand

--- Pushing Macro On ---
Light is on
Coffee machine is on
Coffee machine is making a cup of coffee

--- Pushing Macro Off ---
Light is off
Coffee machine is off
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Our MacroCommand turns on the light and starts the coffee machine, which immediately begins brewing coffee. Note that we can define a set of actions in the Receiver and use them in the execute() method of the ConcreteCommand, as shown in the UML diagram in the "Structure" section.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@Override
    public void execute() {
        coffeeMachine.on();
        coffeeMachine.makeCoffee();
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;






&lt;p&gt;You can check all the design pattern implementations here.&lt;br&gt;
&lt;a href="https://github.com/SotaNoniwa/DesignPattern2" rel="noopener noreferrer"&gt;GitHub Repository&lt;/a&gt;&lt;/p&gt;




&lt;p&gt;P.S.&lt;br&gt;
I'm new to write tech blog, if you have advice to improve my writing, or have any confusing point, please leave a comment!&lt;br&gt;
Thank you for reading :)&lt;/p&gt;

</description>
      <category>design</category>
      <category>designpatterns</category>
      <category>computerscience</category>
      <category>java</category>
    </item>
    <item>
      <title>Singleton Pattern</title>
      <dc:creator>Sota</dc:creator>
      <pubDate>Fri, 22 Nov 2024 01:07:34 +0000</pubDate>
      <link>https://dev.to/sota_333ad4b72095606ab40c/singleton-pattern-2m62</link>
      <guid>https://dev.to/sota_333ad4b72095606ab40c/singleton-pattern-2m62</guid>
      <description>&lt;h2&gt;
  
  
  What is Singleton Pattern?
&lt;/h2&gt;

&lt;blockquote&gt;
&lt;p&gt;The singleton pattern is a creational pattern that ensures a class has only one instance, and provides a global point of access to it.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2&gt;
  
  
  When to use it?
&lt;/h2&gt;

&lt;p&gt;Use Singleton pattern when you want to ensure only one instance of a class exists in application.&lt;/p&gt;

&lt;h2&gt;
  
  
  Problem
&lt;/h2&gt;

&lt;p&gt;Let's try to implement our Singleton pattern.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public class Singleton {

    private static Singleton instance;

    private Singleton() {
    }

    public static Singleton getInstance() {
        if (instance == null) {
            instance = new Singleton();
        }
        return instance;
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;Singleton class holds static variable &lt;code&gt;instance&lt;/code&gt;, this is our one and only instance of Singleton class.&lt;/li&gt;
&lt;li&gt;Constructor is declared as private so that nobody can't instantiate Singleton class except for Singleton class itself.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;getInstance()&lt;/code&gt; returns instance of Singleton class. In this code, instance gets created when it is needed, this is called &lt;strong&gt;lazy instantiation&lt;/strong&gt;.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Can you spot the problem? Think what happens when we're in multithreading environment.&lt;/p&gt;

&lt;p&gt;The problem occurs more than one thread call &lt;code&gt;getInstance()&lt;/code&gt; at the same time. Let's see how it occurs when we have two threads...&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Thread1 checks if instance is null or not, we haven't called &lt;code&gt;getInstance()&lt;/code&gt; before, thus &lt;code&gt;instance == null&lt;/code&gt; is true.&lt;/li&gt;
&lt;li&gt;Thread2 also calls &lt;code&gt;getInstance()&lt;/code&gt; and check if instance is null. Because Thread1 just entered inside &lt;code&gt;if&lt;/code&gt; block and didn't create object, &lt;code&gt;instance&lt;/code&gt; is still null.&lt;/li&gt;
&lt;li&gt;Thread1 instantiates Singleton class with &lt;code&gt;new&lt;/code&gt; keyword.&lt;/li&gt;
&lt;li&gt;Thread2 also instantiates Singleton class.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;We now have two Singleton objects, which is not desired.&lt;/p&gt;

&lt;p&gt;Such a situation is called &lt;strong&gt;race condition&lt;/strong&gt;, where multiple threads attempt to access to shared resources at the same time but its outcome is indeterministic.&lt;/p&gt;

&lt;h2&gt;
  
  
  Solution 1
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public class Singleton {

    private static Singleton instance;

    private Singleton() {
    }

    public static synchronized Singleton getInstance() {
        if (instance == null) {
            instance = new Singleton();
        }
        return instance;
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Solution is just adding &lt;code&gt;synchronized&lt;/code&gt; keyword to &lt;code&gt;getInstance()&lt;/code&gt;. &lt;code&gt;synchronized&lt;/code&gt; keyword can ensure only one thread can enter the method at the time and other threads wait their turn.&lt;/p&gt;

&lt;p&gt;This works fine but synchronization is expensive. synchronization is only needed when &lt;code&gt;getInstance()&lt;/code&gt; is called for the first time since once we get instance of Singleton, &lt;code&gt;getInstance()&lt;/code&gt; won't enter &lt;code&gt;if&lt;/code&gt; block and just return an object that already has been created. After the first time through, synchronization is totally unneeded overhead.&lt;/p&gt;

&lt;h2&gt;
  
  
  Solution 2
&lt;/h2&gt;

&lt;p&gt;We can implement &lt;strong&gt;eager instantiation&lt;/strong&gt; Singleton if our application always creates and uses an instance of Singleton.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public class Singleton {

    // Create an instance when Singleton class is loaded by JVM
    private static Singleton instance = new Singleton();

    private Singleton() {
    }

    public static Singleton getInstance() {
        // instance has already been created
        return instance;
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Solution 3
&lt;/h2&gt;

&lt;p&gt;if performance of getInstance() is an issue (like we pointed out in Solution 1), we can implement &lt;strong&gt;double-checked locking&lt;/strong&gt; Singleton.&lt;br&gt;
As name indicates, this implementation does null-check for our instance twice.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;First check: if instance is null, it enters the block.&lt;/li&gt;
&lt;li&gt;Synchronization: lock on Singleton class object (Class object is a runtime representation of the class), this ensures only one thread at a time executes the synchronized block. The synchronized block represents &lt;strong&gt;critical section&lt;/strong&gt;.&lt;/li&gt;
&lt;li&gt;Second check: this check can't occur at a time because of synchronization.
&lt;/li&gt;
&lt;/ol&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public class Singleton {

    private volatile static Singleton instance;

    private Singleton() {
    }

    public static Singleton getInstance() {
        if (instance == null) { // First check
            synchronized (Singleton.class) { // Synchronization
                if (instance == null) { // Second check
                    instance = new Singleton();
                }
            }
        }
        return instance;
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;h2&gt;
  
  
  Solution 4
&lt;/h2&gt;

&lt;p&gt;Singleton sounds simple but it has many things we have to consider such as synchronization, class loading, reflection and serialization/deserialization issues. Is there any better implementation that resolves these issues? Yes, enum provides simple implementation and resolves all the issues above.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public enum Singleton {
    INSTANCE;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We don't need to write our own private constructor because JVM will instantiate our INSTANCE automatically.&lt;/p&gt;

&lt;h2&gt;
  
  
  Structure
&lt;/h2&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fguazg9wqe7njcbhuv912.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fguazg9wqe7njcbhuv912.png" alt="Image description" width="441" height="281"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Pitfalls
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;Singleton violates the single responsibility principle as it does two jobs, ensuring only one instance exists &amp;amp; providing a global access point to that instance.&lt;/li&gt;
&lt;/ul&gt;




&lt;p&gt;You can check all the design pattern implementations here.&lt;br&gt;
&lt;a href="https://github.com/SotaNoniwa/DesignPattern2" rel="noopener noreferrer"&gt;GitHub Repository&lt;/a&gt;&lt;/p&gt;




&lt;p&gt;P.S.&lt;br&gt;
I'm new to write tech blog, if you have advice to improve my writing, or have any confusing point, please leave a comment!&lt;br&gt;
Thank you for reading :)&lt;/p&gt;

</description>
      <category>computerscience</category>
      <category>java</category>
      <category>design</category>
      <category>designpatterns</category>
    </item>
  </channel>
</rss>
