<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Abdullah Al Noman on Medium]]></title>
        <description><![CDATA[Stories by Abdullah Al Noman on Medium]]></description>
        <link>https://medium.com/@abdullahalnoman1?source=rss-2f9903a311ff------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*rt5FKl0dF1sY1uAjCH65dA.jpeg</url>
            <title>Stories by Abdullah Al Noman on Medium</title>
            <link>https://medium.com/@abdullahalnoman1?source=rss-2f9903a311ff------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 20 Nov 2026 00:00:38 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@abdullahalnoman1/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Iterator Design Pattern]]></title>
            <link>https://abdullahalnoman1.medium.com/iterator-design-pattern-5770609ab180?source=rss-2f9903a311ff------2</link>
            <guid isPermaLink="false">https://medium.com/p/5770609ab180</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[software-design-patterns]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[iterator-pattern]]></category>
            <dc:creator><![CDATA[Abdullah Al Noman]]></dc:creator>
            <pubDate>Fri, 19 Mar 2021 14:28:25 GMT</pubDate>
            <atom:updated>2021-03-19T14:28:25.359Z</atom:updated>
            <content:encoded><![CDATA[<p>Today I am going to discuss a very simple behavioral design pattern called the Iterator design pattern. Almost every programming language has data structure and collection, hence they provide iterator and we iterate over the objects. Sometimes we use for loop or forEach loop to do that but we need to make sure that our implementation should not be exposed. According to the book, the main intent is like</p><p><strong><em>“Provide a way to access the elements of an aggregate object sequentially without exposing its underlying representation. ”</em></strong></p><p>Ok, let&#39;s see some examples of iteration now.</p><pre>// If a simple array is used to store gadgets<br>for (int i = 0; i &lt; gadgetList.length; i++)<br>     Gadget gadget= gadgetList[i]);</pre><pre>// If ArrayList is Java is used, then we would iterate<br>// over them as:<br>for (int i = 0; i &lt; gadgetList.size(); i++)<br>    Gadget gadget= (Gadget)gadgetList.get(i);</pre><p>If we could have some other collection like a tree, set, Map, etc. Then our way of iteration should be changed, that’s why we are going to build a generic way of iterating over a collection of its independent type.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/871/1*tYlnCcgKhcsh7bbWb90JYw.png" /><figcaption>UML Diagram Iterator Pattern</figcaption></figure><p>In this pattern, we have a common interface<strong> Collection </strong>for the client as it decouples it from the implementation of your collection objects. The <strong>GadgetCollection</strong> implements that <strong>createIterator()</strong> method for returning the iterator for its collection. The responsibilities of <strong>ConcreteIterator</strong> named as <strong>GadgetIterator</strong> is to instantiate a <strong>ConcreteIterator</strong> that can iterate over its collection. Consider a situation where you are adding multiple gadgets in an application and you have to traverse and display all the gadgets. So, we are writing the following codes for that.</p><p><strong>Coding Implementation:</strong></p><pre>// Our Model Class<br>public class Gadget {<br>    private String name;<br><br>    public Gadget(String name) {<br>        this.name = name;<br>    }<br><br>    public String getName() {<br>        return name;<br>    }<br>}</pre><pre>// Our Collection Interface <br>public interface Collection {<br>    public Iterator createIterator();<br>}<br>// Concrete Collection Class<br>public class GadgetCollection implements Collection{<br>    static final int <em>MAX_ITEMS </em>= 6;<br>    int numberOfItems = 0;<br>    Gadget[] gadgetList;<br><br>    public GadgetCollection() {<br>        gadgetList = new Gadget[<em>MAX_ITEMS</em>];<br><br>        addGadget(&quot;Phone&quot;);<br>        addGadget(&quot;Tablet&quot;);<br>        addGadget(&quot;Computer&quot;);<br><br>    }<br><br>    private void addGadget(String gadget) {<br>        Gadget gadget1 = new Gadget(gadget);<br>        if(numberOfItems &gt;= <em>MAX_ITEMS</em>){<br>            System.<em>out</em>.println(&quot;Full&quot;);<br>        }else{<br>            gadgetList[numberOfItems] = gadget1;<br>            numberOfItems += 1;<br>        }<br>    }<br><br>    @Override<br>    public Iterator createIterator() {<br>        return new GadgetIterator(gadgetList);<br>    }<br>}</pre><pre>// Iterator Interface</pre><pre>public interface Iterator {<br>    public boolean hasNext();<br>    Object next();<br>}</pre><pre>// Concrete Iterator</pre><pre>public class GadgetIterator implements Iterator{<br>    Gadget[] gadgetList;<br>    int position = 0;<br><br>    public GadgetIterator(Gadget[] gadgetList) {<br>        this.gadgetList = gadgetList;<br>    }<br><br>    @Override<br>    public boolean hasNext() {<br>        if(position &gt;= gadgetList.length || gadgetList[position] == null){<br>            return false;<br>        }else{<br>            return true;<br>        }<br><br>    }<br><br>    @Override<br>    public Object next() {<br>        Gadget gadget = gadgetList[position];<br>        position += 1;<br>        return gadget;<br>    }<br>}</pre><pre>public class GadgetDirectory {<br>    GadgetCollection gadgetCollection;<br><br>    public GadgetDirectory(GadgetCollection gadgetCollection) {<br>        this.gadgetCollection = gadgetCollection;<br>    }<br><br>    public void showGadgets(){<br>        Iterator iterator = gadgetCollection.createIterator();<br>        System.<em>out</em>.println(&quot; ================ Gadgets ============&quot;);<br>        while (iterator.hasNext()){<br>            Gadget gadget = (Gadget) iterator.next();<br>            System.<em>out</em>.println(gadget.getName());<br>        }<br>    }<br>}</pre><pre>public class IteratorClient {<br><br>    public static void main(String[] args) {<br>        GadgetCollection gadgetCollection = new GadgetCollection();<br>        GadgetDirectory gadgetDirectory = new GadgetDirectory(gadgetCollection);<br><br>        gadgetDirectory.showGadgets();<br>    }<br>}</pre><p><strong>SOLID Principles in this pattern:</strong></p><ol><li>You will find Singular Responsibility Principles because you will be able to clean up the client code and the collection by extracting another traversal algorithm into a separate class.</li><li>Open Closed Principles. You can add new types of collections and iterators and pass them without breaking the existing code.</li><li>We don’t have any fat interface in our system so it supports interface segregation principles. Can you find the other solid principles in this pattern !! Look at it closely.</li></ol><p><strong>Relation with other patterns:</strong></p><p>Can you combine both the composite and the iterator pattern together?? Yes, you can use this pattern to traverse the composite tree of the composite pattern.</p><p>Reference:</p><ol><li><a href="https://www.geeksforgeeks.org/iterator-pattern/">https://www.geeksforgeeks.org/iterator-pattern/</a></li><li>Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides. <strong>Design patterns: elements of reusable object-oriented software</strong>. <em>Addison-Wesley Professional, 1995.</em></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5770609ab180" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Composite Design Pattern]]></title>
            <link>https://abdullahalnoman1.medium.com/composite-design-pattern-ebbd48ca8f1e?source=rss-2f9903a311ff------2</link>
            <guid isPermaLink="false">https://medium.com/p/ebbd48ca8f1e</guid>
            <category><![CDATA[solid-principles]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[composite-pattern]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[software-architecture]]></category>
            <dc:creator><![CDATA[Abdullah Al Noman]]></dc:creator>
            <pubDate>Wed, 10 Mar 2021 16:44:49 GMT</pubDate>
            <atom:updated>2021-03-10T16:44:49.490Z</atom:updated>
            <content:encoded><![CDATA[<p><em>“Once you stop dreaming, You start dying” — Bill Johnson</em></p><p>When we write code we think of everything as an object and One object can hold multiple objects like a chain inside the parent object. Every object can be treated as a single instance of the same type of object. The intent is like Compose the object into a tree structure to represent part-whole hierarchies. So we can get a tree structure and every node or leaf can be represented as a single object. When programmers write code for tree-structured data they often discriminate between a leaf node and a branch. This makes the code more complex and the solution to this problem is to write an interface that allows treating complex and primitive objects uniformly.</p><p><em>So, we can use this pattern when we have several tree structure objects and we want to get the specific object or node as an individual object. According to the book, the main intent is like,</em></p><p><strong><em>“ Compose Objects into tree structures to represent part-whole hierarchies. Composite lets client treat individual objects and compositions of objects uniformly” — Design Pattern Book</em></strong></p><p>The main concept is that we can manipulate a single instance of an object as we would manipulate the group of objects. This pattern has four properties,</p><p><strong>Component:</strong> It is the interface for an object in the composition and for accessing and managing its child components.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/281/1*LZAXOXWSihztBtElmGeszQ.png" /><figcaption>Tree Structure</figcaption></figure><p><strong>Leaf: </strong>It represents the leaf object in the composition.</p><p><strong>Composite: </strong>It stores child components and implements the child-related operations in the component interface.</p><p><strong>Client:</strong> It manipulates the object in the compositions through the component interface.</p><p>The client uses the component class interface to interact with the objects in the composition structure. If the recipient is a leaf then the object is handled directly. If it is composite, then it forwards a request to its child component and performs the additional operation.</p><p>Example: <br>Think about a situation you are writing code for an e-commerce software where you are dealing with different gadgets. Suppose you have mobile phones, tablets, laptops, desktops, etc. You can make a tree of those objects and even you can categories them. Finally, you can get the individual object through the composite pattern. Let’s implement this example with code now.</p><pre>// Component Interface to manipulating child components<br>public interface Gadget {<br>    public void showGadgetDetails();<br>}</pre><pre>// Mobile Phone as a leaf<br>public class Mobile implements Gadget{<br>    private String brand;<br>    private String model;<br>    private Double price;<br><br>    public Mobile(String brand, String model, Double price) {<br>        this.brand = brand;<br>        this.model = model;<br>        this.price = price;<br>    }<br><br>    public String getBrand() {<br>        return brand;<br>    }<br><br>    public String getModel() {<br>        return model;<br>    }<br><br>    public Double getPrice() {<br>        return price;<br>    }<br><br>    @Override<br>    public String toString() {<br>        return &quot;Mobile{&quot; +<br>                &quot;brand=&#39;&quot; + brand + &#39;\&#39;&#39; +<br>                &quot;, model=&#39;&quot; + model + &#39;\&#39;&#39; +<br>                &quot;, price=&quot; + price +<br>                &#39;}&#39;;<br>    }<br><br>    @Override<br>    public void showGadgetDetails() {<br>        System.<em>out</em>.println(&quot;Brand Name:  &quot;+ getBrand() + &quot; Model: &quot; + getModel() + &quot; Price: &quot; + getPrice());<br>    }<br>}</pre><pre>// Tablet as a leaf<br>public class Tablet implements Gadget{<br>    private String brand;<br>    private String model;<br>    private Double price;<br><br>    public Tablet(String brand, String model, Double price) {<br>        this.brand = brand;<br>        this.model = model;<br>        this.price = price;<br>    }<br><br>    public String getBrand() {<br>        return brand;<br>    }<br><br>    public String getModel() {<br>        return model;<br>    }<br><br>    public Double getPrice() {<br>        return price;<br>    }<br><br>    @Override<br>    public String toString() {<br>        return &quot;Tablet{&quot; +<br>                &quot;brand=&#39;&quot; + brand + &#39;\&#39;&#39; +<br>                &quot;, model=&#39;&quot; + model + &#39;\&#39;&#39; +<br>                &quot;, price=&quot; + price +<br>                &#39;}&#39;;<br>    }<br><br>    @Override<br>    public void showGadgetDetails() {<br>        System.<em>out</em>.println(&quot;Brand Name:  &quot;+ getBrand() + &quot; Model: &quot; + getModel() + &quot; Price: &quot; + getPrice());<br>    }<br>}</pre><pre>// Our Composite Class <br>public class GadgetDirectory implements Gadget{<br>    private List&lt;Gadget&gt; gadgetList;<br><br>    public GadgetDirectory() {<br>        gadgetList = new ArrayList&lt;&gt;();<br><br>    }<br><br><br>    @Override<br>    public void showGadgetDetails() {<br>        for (Gadget gadget: gadgetList) {<br>            gadget.showGadgetDetails();<br>        }<br>    }<br><br>    public void addGadget(Gadget gadget){<br>        gadgetList.add(gadget);<br>    }<br><br>}<br>// Client Code <br>public class CompositeClient {<br>    public static void main(String[] args) {<br>        Mobile mobile = new Mobile(&quot;Apple&quot;,&quot;Iphone 12 Pro&quot;,1300.00);<br>        Mobile mobile1 = new Mobile(&quot;Samsung&quot;,&quot;S20 Altra&quot;,1400.00);<br><br>        System.<em>out</em>.println(&quot;Mobile phone as an individual Object.&quot;);<br><br>        GadgetDirectory phoneDirectory = new GadgetDirectory();<br>        phoneDirectory.addGadget(mobile);<br>        phoneDirectory.addGadget(mobile1);<br>        phoneDirectory.showGadgetDetails();<br><br>        Tablet tablet = new Tablet(&quot;Samsung&quot;,&quot;Model S5&quot;,700.00);<br>        Tablet tablet1 = new Tablet(&quot;Samsung&quot;,&quot;Model 30&quot;,790.00);<br><br>        System.<em>out</em>.println(&quot;Tablet as an individual Object.&quot;);<br><br>        GadgetDirectory tabletDirectory = new GadgetDirectory();<br>        tabletDirectory.addGadget(tablet);<br>        tabletDirectory.addGadget(tablet1);<br>        tabletDirectory.showGadgetDetails();<br><br>        System.<em>out</em>.println(&quot;All the objects together.&quot;);<br><br>        GadgetDirectory gadgetDirectory = new GadgetDirectory();<br>        gadgetDirectory.addGadget(phoneDirectory);<br>        gadgetDirectory.addGadget(tabletDirectory);<br>        gadgetDirectory.showGadgetDetails();<br><br><br><br>    }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/842/1*WqCTxwhD_S1s5eRjes9tPg.png" /><figcaption>UML Diagram</figcaption></figure><p><strong>SOLID Principles:</strong></p><ol><li>Open Closed Principle, we can introduce a new element type into the application without breaking the existing details.</li><li>It also supports the Interface segregation in our example, if you look insight you will find almost all the principles but some principles are obviously not visible in the UML diagram.</li></ol><p><strong>Relation with other Pattern:</strong></p><ol><li>We can use the iterator pattern to traverse through the child components. that’s how we can make a compound pattern.</li><li>Chain of Responsibility is often used in conjunction with Composite. In this case, when a leaf component gets a request, it may pass it through the chain of all of the parent components down to the root of the object tree.</li></ol><p>Reference:</p><ol><li><a href="https://refactoring.guru/design-patterns/composite">https://refactoring.guru/design-patterns/composite</a></li><li><a href="https://www.geeksforgeeks.org/composite-design-pattern/">https://www.geeksforgeeks.org/composite-design-pattern/</a></li><li>Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides. <strong>Design patterns: elements of reusable object-oriented software</strong>. <em>Addison-Wesley Professional, 1995.</em></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ebbd48ca8f1e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Template Method Pattern]]></title>
            <link>https://abdullahalnoman1.medium.com/template-method-pattern-39e5674e67df?source=rss-2f9903a311ff------2</link>
            <guid isPermaLink="false">https://medium.com/p/39e5674e67df</guid>
            <category><![CDATA[template-method]]></category>
            <category><![CDATA[template-method-pattern]]></category>
            <dc:creator><![CDATA[Abdullah Al Noman]]></dc:creator>
            <pubDate>Wed, 10 Mar 2021 00:52:58 GMT</pubDate>
            <atom:updated>2021-03-10T17:52:27.601Z</atom:updated>
            <content:encoded><![CDATA[<p><em>“If you want to go fast, go alone. If you want to go far, go together”. - African Proverb.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cIQ99WYe5eYj4CJ2eKyJew.jpeg" /></figure><p>Template method pattern is used when we have multiple algorithms that have some common functionality. In general words, the template is like a default structure for doing a specific task. we are using this pattern for the architectural plans and throughout the engineering domain. A template plan can be built on with further variations. From the book, the main intent is like</p><p>“<strong><em>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.</em></strong>”</p><p>We can think about a situation where we are building a solution for the ordering process. We can order online or by going to the store itself. Every order has some common business, we have to collect items from the store, then we have to make a payment and eventually we have to deliver the order to the specific customer. There is an extra additional business is, sometimes the customer wants to wrap their product for sending as a gift. So, we took all the common business in a single method that will be work as a template method.</p><p><strong>Coding Implementation:</strong></p><pre>// abstract template class <br>public abstract class OrderProcessTemplate {<br>    public boolean isGift;<br>    public abstract void doSelect();<br>    public abstract void doPayment();<br><br>    public final void giftWrap(){<br>        try<br>        {<br>            System.<em>out</em>.println(&quot;Gift wrap successful&quot;);<br>        }<br>        catch (Exception e)<br>        {<br>            System.<em>out</em>.println(&quot;Gift wrap unsuccessful&quot;);<br>        }<br>    }<br>    public abstract void doDelivery();<br>    public final void processOrder(boolean isGift){<br>        doSelect();<br>        doPayment();<br>        if(isGift){<br>            giftWrap();<br>        }<br>        doDelivery();<br>    }<br><br>}</pre><pre>// Order from the store </pre><pre>public class StoreOrder extends OrderProcessTemplate{<br>    @Override<br>    public void doSelect() {<br>        System.<em>out</em>.println(&quot;Customer chooses the item from shelf.&quot;);<br>    }<br><br>    @Override<br>    public void doPayment() {<br>        System.<em>out</em>.println(&quot;Pays at counter through cash/POS&quot;);<br>    }<br><br>    @Override<br>    public void doDelivery() {<br>        System.<em>out</em>.println(&quot;Item delivered to in delivery counter.&quot;);<br>    }<br>}</pre><pre>// Order through the online <br>public class NetOrder extends OrderProcessTemplate{<br>    @Override<br>    public void doSelect() {<br>        System.<em>out</em>.println(&quot;Item added to the online shopping cart&quot;);<br>        System.<em>out</em>.println(&quot;Get gift wrap preference&quot;);<br>        System.<em>out</em>.println(&quot;Get delivery address.&quot;);<br>    }<br><br>    @Override<br>    public void doPayment() {<br>        System.<em>out</em>.println<br>                (&quot;Online Payment through Netbanking, card or Paytm&quot;);<br>    }<br><br>    @Override<br>    public void doDelivery() {<br>        System.<em>out</em>.println<br>                (&quot;Ship the item through post to delivery address&quot;);<br>    }<br>}</pre><pre>// Final Client Class to invoke our ordering system<br>public class TemplateMethodPatternClient {<br>    public static void main(String[] args) {<br>        OrderProcessTemplate netOrder = new NetOrder();<br>        netOrder.processOrder(true);<br>        System.<em>out</em>.println();<br>        OrderProcessTemplate storeOrderProcessTemplate = new StoreOrder();<br>        storeOrderProcessTemplate.processOrder(true);<br>    }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/770/1*_qJFdJIq_oK4LfafWEG4yQ.png" /><figcaption>UML Diagram</figcaption></figure><p>The <strong>abstract class</strong> should contain the <strong>template method,</strong> which should be made final so that it cannot be overridden. This template method makes use of other operations available in order to run the algorithm but is decoupled for the actual implementation of these methods. All operations used by this template method are made abstract, so their implementation is deferred to subclasses. The concrete classes implement all the abstract methods written in the abstract class.</p><p>The template pattern makes us remember about the Hollywood Principle, “Don’t call us we will call you”. The template method in the parent class controls the overall process, “calling” subclass methods when necessary. The Hollywood principle avoids low-level components depending on high-level components and instead gives these low-level classes (ConcreteClass) a way of hooking into the parent class (AbstractClass). Hence, it supports the Dependency inversion principle.</p><p>This Pattern supports the open-closed principle by adding another order process as a concrete class. It also serves the singular responsibility principle. It might violate the Liskov substitution principle by suppressing a default step implementation via a subclass.</p><p><strong>Relation with another design principle:</strong></p><ol><li>It looks like the strategy pattern but the strategy pattern selects the algorithm at the run time and works at the object level on the other side the Template method selects the algorithm at compile time so works at a class level.</li><li>It has a relation with the factory method, which is the specialization of the template method.</li></ol><p>References :</p><ol><li><a href="https://www.geeksforgeeks.org/template-method-design-pattern/">https://www.geeksforgeeks.org/template-method-design-pattern/</a></li><li>Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides. <strong>Design patterns: elements of reusable object-oriented software</strong>. <em>Addison-Wesley Professional, 1995.</em></li><li><a href="https://github.com/abdullahalnoman8/software_architecture_code_sample/tree/main/src/com/softwaredesignpatterns/template_pattern/example_1">https://github.com/abdullahalnoman8/software_architecture_code_sample/tree/main/src/com/softwaredesignpatterns/template_pattern/example_1</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=39e5674e67df" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Software Design Pattern and Strategy Design pattern]]></title>
            <link>https://abdullahalnoman1.medium.com/software-design-pattern-and-strategy-design-pattern-4e6ddc90ae63?source=rss-2f9903a311ff------2</link>
            <guid isPermaLink="false">https://medium.com/p/4e6ddc90ae63</guid>
            <category><![CDATA[strategy-design-pattern]]></category>
            <dc:creator><![CDATA[Abdullah Al Noman]]></dc:creator>
            <pubDate>Tue, 09 Mar 2021 23:58:53 GMT</pubDate>
            <atom:updated>2021-03-10T13:36:20.426Z</atom:updated>
            <content:encoded><![CDATA[<p>Let’s start with a quote, <br><strong><em>“ </em></strong><em>If you are not prepared to be wrong, you never come up with anything original.</em><strong><em>”<br></em></strong> — <em>Sir Ken Robinson.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*OV2xAAETTsJi7Y1GA3DgSw.jpeg" /><figcaption>Software Architecture</figcaption></figure><p>The software design pattern is a reusable solution to the commonly occurring problem within a given context in Software Architecture. In software design, we can think about an object and organize the object in such a way that it provides a strong solution for a system. There are three categories of this design pattern.</p><p>1. Creational Design Pattern</p><p>2. Structural Design Pattern &amp;</p><p>3. Behavioral Design Pattern.</p><p><strong>Creational Design Pattern:</strong> It basically works for creating the object in such a manner so that the created object is flexible and reusable in the existing codes.</p><p><strong>Structural Design Pattern:</strong> It assembles the created objects and classes into a larger structure, while it keeps the structures flexible and efficient.<br> <br> <strong>Behavioral Design Pattern:</strong> It deals with the algorithms and the assignment of responsibilities between objects.</p><p>Now If we summarize the above categories, we can find that we can create objects, object structure and compose those in a way that defines a specific behavior in the software which is a better solution for a specific problem. I will discuss every pattern of software design with examples step by step with implementations.</p><p><strong>Strategy Design Pattern:</strong></p><p>This under the behavioral design pattern which defines the behavior of objects and algorithm to solve a certain problem in software. It can come to our mind that when we will use this design pattern. Can we think??? Ok, let’s think about you are writing code where there are several objects that are almost the same type and you have to select the object you need at your run time. You can do this with this design pattern. From the book, the main intent of this pattern is like,<br> <br> <strong><em>“Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from clients that use it.”</em></strong></p><p><strong>Examples: <br></strong> 1. Java <strong><em>Collections.sort()</em></strong>, we can use this method for different implementations of object sorting. In the back of this method there are several algorithms are written by the JDK developers which help to sort our objects.</p><p>2. Think about we are writing code for an application where we have to write the Map API for routing, and you would need to select the path as your needs. For instance, if you look closely at the Google Map application you will see that you can select the direction as walking, bicycling, car, train, and tram as you need. In the back, you can use this pattern for selecting the path you need.</p><p>3. Suppose we are developing an e-commerce application and we need to implement the payment gateway for that, multiple payment systems can be added in the future as well but here the algorithm will not change. We will be able to add a new payment method to our design. So, we cope with anticipated and unanticipated changes to the algorithms and new algorithms or want to avoid changing code and/or breaking the existing code.</p><p><strong>Implementation:</strong></p><pre>// Strategy interface<br>public interface  PaymentStrategy {<br>    public void pay(double amount);<br>}</pre><pre>// Paypal Payment Alogorithm<br>public class PaypalStrategy implements PaymentStrategy{<br><br>    private String email;<br>    private String password;<br><br>    public PaypalStrategy(String email, String password) {<br>        this.email = email;<br>        this.password = password;<br>    }<br><br>    @Override<br>    public void pay(double amount) {<br>        System.<em>out</em>.println(amount + &quot; paid by paypal&quot;);<br>    }<br>}</pre><pre>// CreditCard Payment Algorithm<br>public class CreditCardStrategy implements PaymentStrategy{<br><br>    private String name;<br>    private String cardNumber;<br>    private String cvv;<br>    private LocalDate dateOfExpiry;<br><br>    public CreditCardStrategy(String name, String cardNumber, String   cvv, LocalDate dateOfExpiry) {<br>        this.name = name;<br>        this.cardNumber = cardNumber;<br>        this.cvv = cvv;<br>        this.dateOfExpiry = dateOfExpiry;<br>    }<br><br>    @Override<br>    public void pay(double amount) {<br>        System.<em>out</em>.println(amount + &quot; Paid by credit card&quot;);<br>    }<br>}</pre><pre><br>// Item </pre><pre>public class Item {<br>    private String name;<br>    private String itemCode;<br>    private double itemPrice;<br><br>    public Item(String name, String itemCode, double itemPrice) {<br>        this.name = name;<br>        this.itemCode = itemCode;<br>        this.itemPrice = itemPrice;<br>    }<br><br>    public String getName() {<br>        return name;<br>    }<br><br>    public String getItemCode() {<br>        return itemCode;<br>    }<br><br>    public double getItemPrice() {<br>        return itemPrice;<br>    }<br>}</pre><pre>// Adding and calculating item price in the cart</pre><pre>public class ShoppingCart {<br>    List&lt;Item&gt; itemList;<br><br>    public ShoppingCart() {<br>        this.itemList = new ArrayList&lt;&gt;();<br>    }<br><br>    public void addItem(Item item){<br>        itemList.add(item);<br>    }<br>    public void removeItem(Item item){<br>        itemList.remove(item);<br>    }<br><br>    public double amountCalculation(){<br>        double sum = 0.0;<br>        for (Item item: itemList) {<br>            sum +=item.getItemPrice();<br>        }<br>        return sum;<br>    }<br><br>    public void paymentStrategy(PaymentStrategy paymentStrategy){<br>        double amount = amountCalculation();<br>        paymentStrategy.pay(amount);<br>    }<br>}</pre><pre>// Client Invocation for testing</pre><pre>public class ShoppingCartDemo{<br>    public static void main(String[] args) {<br>        ShoppingCart shoppingCart  = new ShoppingCart();<br>        Item item1 = new Item(&quot;Coat&quot;,&quot;234234&quot;, 3443);<br>        Item item2 = new Item(&quot;Shoe&quot;,&quot;543543&quot;,23423);<br><br>        shoppingCart.addItem(item1);<br>        shoppingCart.addItem(item2);<br><br>        LocalDate localDate = LocalDate.<em>now</em>();<br>        shoppingCart.paymentStrategy(new PaypalStrategy(&quot;abc@gmail.com&quot;,&quot;abc&quot;));<br>        shoppingCart.paymentStrategy(new CreditCardStrategy(&quot;Card Name&quot;,<br>                &quot;Card Number&quot;,<br>                &quot;234&quot;,localDate.plusYears(4)));<br><br>    }<br><br>}</pre><p>If we look at insight we will find that it supports almost all the SOLID principles in some way.</p><ol><li>The responsibility for the implementation of a concrete strategy is decoupled from the context that uses this structure.</li><li>It supports OCP as we don’t need to make a change to use a new type of strategy.</li><li>All the concrete strategies are using the same interface and should be substitutable without affecting the system&#39;s correctness.</li><li>It supports the interface segregation principle as we don’t have any fate interface.</li><li>Both the context and the concrete strategies depend on an abstract interface and are not directly coupled.</li></ol><p>References and Books to know more:</p><ol><li>Eric Freeman, Elisabeth Robson, Kathy Sierra, and Bert Bates. Head First Design Patterns. O’ Reilly &amp; Associates, Inc., 2014</li><li>Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides. Design patterns: elements of reusable object-oriented software. Addison-Wesley Professional, 1995.</li><li><a href="https://www.journaldev.com/1754/strategy-design-pattern-in-java-example-tutorial">https://www.journaldev.com/1754/strategy-design-pattern-in-java-example-tutorial</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4e6ddc90ae63" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>