<?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 Hruday⚡️ on Medium]]></title>
        <description><![CDATA[Stories by Hruday⚡️ on Medium]]></description>
        <link>https://medium.com/@AdvanceQuest_?source=rss-f1ae2fdec112------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*qNPzzLorHEy-tu1Gs-9kfQ.jpeg</url>
            <title>Stories by Hruday⚡️ on Medium</title>
            <link>https://medium.com/@AdvanceQuest_?source=rss-f1ae2fdec112------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 18:59:25 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@AdvanceQuest_/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[AWS Networking Explained: From IP Addresses to VPCs, Subnets, Routing, NAT & Security]]></title>
            <link>https://medium.com/@AdvanceQuest_/aws-networking-explained-from-ip-addresses-to-vpcs-subnets-routing-nat-security-8bf92bfcee48?source=rss-f1ae2fdec112------2</link>
            <guid isPermaLink="false">https://medium.com/p/8bf92bfcee48</guid>
            <dc:creator><![CDATA[Hruday⚡️]]></dc:creator>
            <pubDate>Sun, 20 Sep 2026 14:23:04 GMT</pubDate>
            <atom:updated>2026-09-20T14:23:04.084Z</atom:updated>
            <content:encoded><![CDATA[<p>AWS networking becomes much easier once you stop looking at VPC, subnets, route tables, NAT, and gateways as separate services.</p><p>They are all pieces of one simple problem:</p><blockquote><strong><em>How does one computer find and communicate with another computer?</em></strong></blockquote><p>Let’s start with basic networking and gradually map those concepts to AWS.</p><h3>1. IP Addresses: How computers identify each other</h3><p>An <strong>IP address</strong> identifies a device on a network.</p><p>For example:</p><pre>192.168.1.10</pre><p>There are two major versions of IP.</p><h3>IPv4</h3><p>IPv4 uses 32 bits.</p><p>Examples:</p><pre>10.0.0.10<br>172.16.5.20<br>192.168.1.50</pre><h3>IPv6</h3><p>IPv6 uses 128 bits and provides a much larger address space.</p><p>Example:</p><pre>2001:db8:1234::10</pre><p>AWS VPCs can use IPv4, IPv6, or both.</p><h3>2. Private and Public IP Addresses</h3><p>A <strong>private IP address</strong> is used for communication inside private networks and is not directly routable over the public internet.</p><p>The three RFC 1918 private IPv4 ranges are:</p><pre>10.0.0.0      – 10.255.255.255<br>172.16.0.0    – 172.31.255.255<br>192.168.0.0   – 192.168.255.255</pre><p>So:</p><pre>10.0.0.10      ✅ Private<br>172.16.5.20    ✅ Private<br>192.168.1.50   ✅ Private</pre><p>But:</p><pre>172.15.1.10    ❌ Not part of the private range<br>172.32.1.10    ❌ Not part of the private range</pre><p>A <strong>public IP address</strong>, on the other hand, can be used to communicate over the public internet, subject to routing and security controls.</p><h3>3. What is a Network?</h3><p>A network is a collection of devices that can communicate with each other using networking protocols.</p><p>For example:</p><pre>PC 1 ──┐<br>       │<br>PC 2 ──┼── Switch<br>       │<br>Server ┘</pre><p>A <strong>switch</strong> primarily connects devices within a local network and forwards traffic using MAC addresses.</p><p>But what happens when PC1 wants to talk to a computer outside its local network?</p><p>For example:</p><pre>PC 1<br>192.168.1.10<br>wants to reach<br>8.8.8.8</pre><p>The destination isn’t in its local network.</p><p>The traffic therefore needs to go to a <strong>router/default gateway</strong>, which can forward it toward another network.</p><p>This leads to one of the most important networking concepts:</p><blockquote><strong><em>Local communication and communication with another network require different paths.</em></strong></blockquote><h3>4. Switch vs Router</h3><p>A simple way to remember them:</p><h3>Switch</h3><p>Connects devices <strong>within a local network</strong>.</p><pre>PC ──┐<br>     ├── Switch<br>PC ──┘</pre><h3>Router</h3><p>Connects <strong>different networks</strong> and decides where IP packets should go.</p><pre>Network A<br>    │<br>    ▼<br> Router<br>    │<br>    ▼<br>Network B</pre><p>In real networks, routing information tells the router where traffic should be sent.</p><p>AWS gives us a virtual version of this idea.</p><h3>5. What is a Subnet?</h3><p>A <strong>subnet is a smaller network created from a larger IP network</strong>.</p><p>Suppose we have:</p><pre>10.0.0.0/16</pre><p>We can divide it into:</p><pre>10.0.1.0/24<br>10.0.2.0/24</pre><p>So conceptually:</p><pre>10.0.0.0/16<br>│<br>├── 10.0.1.0/24<br>└── 10.0.2.0/24</pre><p>Why divide a network?</p><p>Because different resources may need different levels of isolation, routing, and security.</p><p>For example:</p><pre>Public-facing resources<br>        ↓<br>Public subnet<br><br>Backend/database resources<br>        ↓<br>Private subnet</pre><h3>6. What is a VPC?</h3><p>Now we can move into AWS.</p><h3>VPC = Virtual Private Cloud</h3><p>A VPC is your <strong>logically isolated virtual network inside AWS</strong>.</p><p>You define its IP address range.</p><p>For example:</p><pre>VPC<br>10.0.0.0/16</pre><p>Then divide it into subnets:</p><pre>VPC: 10.0.0.0/16<br>├── Public Subnet<br>│   10.0.1.0/24<br>│<br>└── Private Subnet<br>    10.0.2.0/24</pre><p>Your EC2 instances, load balancers, databases, and other networking resources can be placed into these subnets.</p><p><strong>In AWS, each subnet belongs to a single Availability Zone.</strong></p><h3>7. What is a Route Table?</h3><p>A route table is essentially a set of <strong>traffic instructions</strong>.</p><p>It answers:</p><blockquote><strong><em>“For this destination, where should the traffic go?”</em></strong></blockquote><p>For example:</p><pre>Destination        Target<br>10.0.0.0/16    -   Local<br>0.0.0.0/0      -   Internet Gateway</pre><p>The first route means:</p><pre>Traffic destined for 10.0.0.0/16<br>        ↓<br>Stay inside the VPC</pre><p>The second means:</p><pre>Traffic destined for anything else<br>        ↓<br>Send it toward the Internet Gateway</pre><p>AWS provides a virtual router inside a VPC. Route tables control how that router directs traffic.</p><p>Every subnet is associated with a route table.</p><h3>8. Public Subnet</h3><p>A subnet becomes <strong>public</strong> when its route table has a route to an Internet Gateway.</p><p>For example:</p><pre>Public Route Table<br>10.0.0.0/16  →  Local<br>0.0.0.0/0    →  Internet Gateway</pre><p>The important route is:</p><pre>0.0.0.0/0 → Internet Gateway</pre><p>It means:</p><blockquote><em>“For destinations outside the VPC, use the Internet Gateway.”</em></blockquote><p>For an IPv4 EC2 instance to communicate directly with the internet through the IGW, it also needs a public IPv4 address.</p><p>So:</p><pre>EC2<br> ↓<br>Public Subnet<br> ↓<br>Route Table<br> ↓<br>Internet Gateway<br> ↓<br>Internet</pre><h3>9. Private Subnet</h3><p>Now imagine we have a database or backend server that shouldn’t be directly reachable from the public internet.</p><p>We put it in a private subnet.</p><p>Its route table might look like:</p><pre>Private Route Table<br>10.0.0.0/16  →  Local<br>0.0.0.0/0    →  NAT Gateway</pre><p>Notice the difference.</p><p>The private subnet does <strong>not</strong> have:</p><pre>0.0.0.0/0 → Internet Gateway</pre><p>Instead, internet-bound IPv4 traffic goes through the NAT Gateway.</p><h3>10. What is a NAT Gateway?</h3><p>NAT stands for:</p><blockquote><strong><em>Network Address Translation</em></strong></blockquote><p>Suppose an EC2 instance in the private subnet has:</p><pre>10.0.2.10</pre><p>It wants to download something from the internet.</p><p>A private IP cannot be used directly as a public internet destination.</p><p>So the request goes through a <strong>NAT Gateway</strong>.</p><p>The NAT Gateway translates the source address so the request can go out to the internet.</p><p>The simplified flow is:</p><pre>Private EC2<br>     ↓<br>Private Route Table<br>     ↓<br>NAT Gateway<br>     ↓<br>Internet Gateway<br>     ↓<br>Internet</pre><p>The response comes back through the NAT mechanism and is delivered to the private instance.</p><p>The important idea is:</p><blockquote><strong><em>NAT allows private IPv4 resources to initiate outbound internet connections without giving those resources direct internet connectivity.</em></strong></blockquote><h3>11. Where does the NAT Gateway go?</h3><p>This is a common point of confusion.</p><p>The NAT Gateway is placed in the <strong>public subnet</strong>.</p><p>Why?</p><p>Because it needs its own path to the internet.</p><p>So our AWS architecture becomes:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FBXf7mSNaqqOslqq5KBw3w.png" /></figure><p>This single diagram captures most of the AWS networking concepts we have discussed.</p><h3>12. What happens inside the VPC?</h3><p>Suppose:</p><pre>EC2-A = 10.0.1.10<br>EC2-B = 10.0.2.10</pre><p>Both belong to:</p><pre>10.0.0.0/16</pre><p>The route table already has:</p><pre>10.0.0.0/16 → Local</pre><p>Therefore, traffic between them can stay inside the VPC.</p><p>It does not need to travel through:</p><pre>NAT Gateway<br>Internet Gateway<br>Public Internet</pre><p>So:</p><blockquote><strong><em>The local route handles communication within the VPC, while other routes handle traffic leaving the VPC or going to other networks.</em></strong></blockquote><h3>13. Security Group</h3><p>Routing answers:</p><blockquote><strong><em>Where should the traffic go?</em></strong></blockquote><p>A Security Group answers:</p><blockquote><strong><em>Is this traffic allowed to reach this resource?</em></strong></blockquote><p>For example, suppose an application server runs on port 8080.</p><p>You might allow:</p><pre>Inbound<br>TCP<br>Port: 8080<br>Source: Application Load Balancer</pre><p>and not allow arbitrary sources.</p><p>Security Groups are associated with network interfaces/resources and are <strong>stateful</strong>.</p><p>That means return traffic for an allowed connection is automatically allowed.</p><p>Think of it as:</p><pre>Traffic<br>   ↓<br>Security Group<br>   ↓<br>Allowed / Not allowed<br>   ↓<br>Resource</pre><h3>14. Network ACL</h3><p>A <strong>Network Access Control List (NACL)</strong> is another security layer, but it operates at the <strong>subnet level</strong>.</p><p>The key difference:</p><pre>Security Group → Resource level<br>NACL           → Subnet level</pre><p>A NACL can contain both:</p><pre>ALLOW<br>DENY</pre><p>rules.</p><p>Unlike Security Groups, NACLs are <strong>stateless</strong>, so return traffic needs its own rule.</p><p>Rules are evaluated in ascending rule-number order until a matching rule is found.</p><p>A simple mental model:</p><pre>VPC<br> │<br> ▼<br>NACL<br> │        ← subnet-level filtering<br> ▼<br>Subnet<br> │<br> ▼<br>Security Group<br> │        ← resource-level filtering<br> ▼<br>EC2</pre><h3>15. Security Group vs NACL</h3><p>Security GroupNACLApplies toResource/network interfaceSubnetRulesAllowAllow + DenyStatefulYesNoReturn trafficAutomatically handledMust be explicitly allowedTypical purposeProtect individual workloadsControl subnet-level traffic</p><h3>16. What about IPv6?</h3><p>IPv6 uses a much larger address space and has a different approach to internet connectivity.</p><p>For IPv4, we commonly see:</p><pre>0.0.0.0/0</pre><p>For IPv6, the equivalent default route is:</p><pre>::/0</pre><p>An IPv6 subnet can route internet traffic through an Internet Gateway.</p><p>For outbound-only IPv6 connectivity, AWS provides an <strong>egress-only internet gateway</strong>.</p><p>This is different from the IPv4 NAT Gateway model.</p><h3>17. The Mental Model</h3><p>At this point, you can think about AWS networking like this:</p><pre>IP Address<br>    ↓<br>Identifies a destination<br><br>Subnet<br>    ↓<br>Divides a larger network<br><br>VPC<br>    ↓<br>Your virtual network in AWS <br><br>Route Table<br>    ↓<br>Decides where traffic should go <br><br>Internet Gateway<br>    ↓<br>Provides internet connectivity for the VPC <br><br>NAT Gateway<br>    ↓<br>Provides outbound IPv4 internet access for private resources <br><br>Security Group<br>    ↓<br>Controls traffic to/from resources (resource level)<br><br>NACL<br>    ↓<br>Controls traffic at the subnet level</pre><p>And the three flows worth remembering are:</p><h3>Communication inside the VPC</h3><pre>Resource<br>   ↓<br>Local Route<br>   ↓<br>Another resource in the VPC</pre><h3>Public resource accessing the internet</h3><pre>Resource<br>   ↓<br>Public Subnet<br>   ↓<br>Route Table<br>   ↓<br>Internet Gateway<br>   ↓<br>Internet</pre><h3>Private resource accessing the internet</h3><pre>Resource<br>   ↓<br>Private Subnet<br>   ↓<br>Route Table<br>   ↓<br>NAT Gateway<br>   ↓<br>Internet Gateway<br>   ↓<br>Internet</pre><h3>Final Takeaway</h3><p>AWS networking is not really a collection of isolated services.</p><p>It’s a flow.</p><p><strong>IP addresses</strong> identify destinations.</p><p><strong>Subnets</strong> divide networks.</p><p>A <strong>VPC</strong> gives you an isolated virtual network.</p><p><strong>Route tables</strong> decide where traffic should go.</p><p>An <strong>Internet Gateway</strong> provides a path between the VPC and the internet.</p><p>A <strong>NAT Gateway</strong> allows private IPv4 resources to initiate outbound internet connections.</p><p>A <strong>Security Group</strong> controls traffic at the resource level.</p><p>A <strong>NACL</strong> controls traffic at the subnet level.</p><p>Once you understand how traffic moves from:</p><p><strong>source → subnet → route table → gateway → destination</strong></p><p>the individual AWS networking services become much easier to understand.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8bf92bfcee48" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Facade Design Pattern — Simplify a Complex Subsystem]]></title>
            <link>https://medium.com/@AdvanceQuest_/facade-design-pattern-simplify-a-complex-subsystem-a3ee1b14e9c9?source=rss-f1ae2fdec112------2</link>
            <guid isPermaLink="false">https://medium.com/p/a3ee1b14e9c9</guid>
            <dc:creator><![CDATA[Hruday⚡️]]></dc:creator>
            <pubDate>Sat, 19 Sep 2026 15:21:04 GMT</pubDate>
            <atom:updated>2026-09-19T15:21:04.360Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8juBJVN1G7yaaqKfbQOPbA.png" /></figure><p>Imagine placing an online order.</p><p>From the user’s perspective, it is simply:</p><pre>Place Order</pre><p>But behind that single action, several things may happen:</p><pre>Check Inventory<br>      ↓<br>Process Payment<br>      ↓<br>Create Shipment<br>      ↓<br>Send Notification</pre><p>The user doesn’t need to know how all these systems work together.</p><p>This is exactly the problem the <strong>Facade Design Pattern</strong> solves.</p><h3>What is the Facade Pattern?</h3><p>The textbook definition is:</p><blockquote><strong><em>“The Facade Pattern provides a unified interface to a set of interfaces in a subsystem.”</em></strong></blockquote><p>In simple words:</p><blockquote><strong><em>Facade provides a simple, high-level interface to a complex subsystem.</em></strong></blockquote><p>Instead of making the client interact with many classes directly, we give it <strong>one simple entry point</strong>.</p><p>The complexity still exists — we simply hide it behind the Facade.</p><h3>The Problem</h3><p>Suppose we have these services:</p><pre>class InventoryService {<br>    public boolean isAvailable(String productId) {<br>        return true;<br>    }<br>}<br><br>class PaymentService {<br>    public void pay(String userId, double amount) {<br>        System.out.println(&quot;Payment processed&quot;);<br>    }<br>}<br><br>class ShippingService {<br>    public void createShipment(String productId) {<br>        System.out.println(&quot;Shipment created&quot;);<br>    }<br>}<br><br>class NotificationService {<br>    public void sendConfirmation(String userId) {<br>        System.out.println(&quot;Confirmation sent&quot;);<br>    }<br>}</pre><p>Without a Facade, the client has to understand all of them:</p><pre>InventoryService inventory = new InventoryService();<br>PaymentService payment = new PaymentService();<br>ShippingService shipping = new ShippingService();<br>NotificationService notification = new NotificationService();<br><br>if (inventory.isAvailable(&quot;P101&quot;)) {<br>    payment.pay(&quot;U101&quot;, 1000);<br>    shipping.createShipment(&quot;P101&quot;);<br>    notification.sendConfirmation(&quot;U101&quot;);<br>}</pre><p>The client now knows:</p><ul><li>which services are required</li><li>which order they should be called in</li><li>how they interact</li><li>what conditions need to be checked</li></ul><p>That’s unnecessary complexity.</p><h3>The Facade</h3><p>We introduce a single class that coordinates everything:</p><pre>class OrderFacade {<br>    private final InventoryService inventory;<br>    private final PaymentService payment;<br>    private final ShippingService shipping;<br>    private final NotificationService notification;<br>    public OrderFacade(<br>            InventoryService inventory,<br>            PaymentService payment,<br>            ShippingService shipping,<br>            NotificationService notification) {<br>        this.inventory = inventory;<br>        this.payment = payment;<br>        this.shipping = shipping;<br>        this.notification = notification;<br>    }<br>    public void placeOrder(<br>            String userId,<br>            String productId,<br>            double amount) {<br>        if (!inventory.isAvailable(productId)) {<br>            System.out.println(&quot;Product unavailable&quot;);<br>            return;<br>        }<br>        payment.pay(userId, amount);<br>        shipping.createShipment(productId);<br>        notification.sendConfirmation(userId);<br>    }<br>}</pre><p>Now the client becomes much simpler:</p><pre>OrderFacade orderFacade =<br>        new OrderFacade(<br>            new InventoryService(),<br>            new PaymentService(),<br>            new ShippingService(),<br>            new NotificationService()<br>        );<br><br>orderFacade.placeOrder(&quot;U101&quot;, &quot;P101&quot;, 1000);</pre><p>The flow is:</p><pre>Client<br>   ↓<br>OrderFacade<br>   ↓<br>Inventory<br>   ↓<br>Payment<br>   ↓<br>Shipping<br>   ↓<br>Notification</pre><p>The client only needs to understand:</p><pre>OrderFacade.placeOrder()</pre><h3>What Exactly Is the Facade Doing?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*1U28XZHciw3VyR3T" /></figure><p>The Facade is <strong>not replacing</strong> the underlying services.</p><p>The services still exist:</p><pre>InventoryService<br>PaymentService<br>ShippingService<br>NotificationService</pre><p>The Facade simply <strong>coordinates them behind a simpler interface</strong>.</p><p>Before:</p><pre>Client<br> ├── InventoryService<br> ├── PaymentService<br> ├── ShippingService<br> └── NotificationService</pre><p>After:</p><pre>Client<br>   ↓<br>OrderFacade<br>   ↓<br>┌───────────────────────────────┐<br>│ Inventory                     │<br>│ Payment                       │<br>│ Shipping                      │<br>│ Notification                  │<br>└───────────────────────────────┘</pre><p>So the complexity hasn’t disappeared.</p><p><strong>It has been encapsulated behind the Facade.</strong></p><h3>Why Is This Useful?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/534/0*jyiJF_VOHIMp3PtW" /></figure><p>Imagine five different clients need to place an order.</p><p>Without a Facade, each client may need to know:</p><pre>Check inventory<br>→ Process payment<br>→ Create shipment<br>→ Send notification</pre><p>That means the same workflow knowledge gets repeated.</p><p>With a Facade:</p><pre>Client A ──┐<br>Client B ──┤<br>Client C ──┼──→ OrderFacade<br>Client D ──┤<br>Client E ──┘</pre><p>If the workflow changes later:</p><pre>Check inventory<br>→ Reserve product<br>→ Process payment<br>→ Create shipment<br>→ Send notification</pre><p>we can update the workflow inside the Facade instead of forcing every client to understand the change.</p><h3>Facade and the Law of Demeter</h3><p>Facade also fits well with the <strong>Law of Demeter</strong>, often summarized as:</p><blockquote><strong><em>“Talk to your immediate friends, not your friends’ friends.”</em></strong></blockquote><p>The idea is to avoid making a client depend on too many internal objects.</p><p>Without a Facade, the client directly coordinates several internal services.</p><p>With the Facade, the client talks to its immediate collaborator — OrderFacade — instead of directly coordinating the subsystem.</p><p>The goal is to <strong>reduce unnecessary coupling and keep internal knowledge out of the client.</strong></p><h3>Facade vs Adapter vs Decorator vs Proxy</h3><p>These patterns can look similar because they all sit between a client and another object/system.</p><p><strong>Facade</strong> → Simplifies a complex subsystem<br> <strong>Adapter</strong> → Makes incompatible interfaces work together<br> <strong>Decorator</strong> → Adds behavior to an existing object<br> <strong>Proxy</strong> → Controls access to an object</p><p>A simple way to remember them:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*AM3kAG56rGKlcBnV" /></figure><h3>The key difference</h3><p>A Facade <strong>does not need to implement the same interface as the subsystem classes</strong>.</p><p>It creates a <strong>new, simpler interface</strong> for the client.</p><h3>When Should You Use Facade?</h3><p>Facade is useful when:</p><ul><li>A subsystem contains many classes and interactions.</li><li>Clients shouldn’t need to understand that complexity.</li><li>The same complex workflow is used in multiple places.</li><li>You want to reduce coupling between clients and internal classes.</li><li>You want to provide a clean high-level entry point.</li></ul><p>Common examples include:</p><pre>Order processing<br>Payment workflows<br>Compiler systems<br>Media processing<br>Database operations<br>Authentication workflows</pre><h3>One Important Detail</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/507/0*2ous-WVSPBfzzwdW" /></figure><p>A Facade doesn’t prevent the underlying classes from being used directly.</p><p>For example:</p><pre>Client<br>   ↓<br>OrderFacade<br>   ↓<br>PaymentService</pre><p>is the normal simplified path.</p><p>But the PaymentService can still exist independently and may be used directly when necessary.</p><p>The Facade is a <strong>convenient high-level entry point</strong>, not necessarily the only entry point.</p><h3>The Building Analogy</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/744/0*9HZVVeWoCY4qtZ7Y" /></figure><p>Think about a building.</p><p>Behind the front facade, there may be:</p><pre>Plumbing<br>Electrical wiring<br>Foundation<br>Rooms<br>Pipes<br>Heating</pre><p>You don’t need to understand all of them just to enter the building.</p><p>You interact with the <strong>facade</strong>.</p><p>The same idea applies in software:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/380/0*6j45YbxyPlOP2sT1" /></figure><p>The complexity is still there.</p><p><strong>The Facade simply gives the client a much simpler way to interact with it.</strong></p><h3>Final Mental Model</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/338/0*BrrwBOvt2qiOssJW" /></figure><p>Remember these three things:</p><pre>Complex subsystem<br>       ↓<br>Simple high-level interface<br>       ↓<br>Client interacts with the Facade</pre><p>Or even simpler:</p><blockquote><strong><em>Facade = Simple interface + complex subsystem behind it.</em></strong></blockquote><p>The client knows <strong>what it wants</strong>.</p><p>The Facade knows <strong>how to make it happen</strong>.</p><p>That is the <strong>Facade Design Pattern</strong>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a3ee1b14e9c9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Chain of Responsibility Design Pattern — Pass the Request Until Someone Handles It]]></title>
            <link>https://medium.com/@AdvanceQuest_/chain-of-responsibility-design-pattern-pass-the-request-until-someone-handles-it-53728f6b02a5?source=rss-f1ae2fdec112------2</link>
            <guid isPermaLink="false">https://medium.com/p/53728f6b02a5</guid>
            <dc:creator><![CDATA[Hruday⚡️]]></dc:creator>
            <pubDate>Tue, 08 Sep 2026 16:04:43 GMT</pubDate>
            <atom:updated>2026-09-08T16:04:43.370Z</atom:updated>
            <content:encoded><![CDATA[<p>Imagine you walk into an ATM and request <strong>₹2,000</strong>.</p><p>The ATM doesn’t necessarily have one component responsible for every withdrawal.</p><p>Different handlers may be responsible for different denominations:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pk8EyyWPBe7HFjVVUW9lUw.png" /></figure><p>The important part is:</p><blockquote><strong><em>The sender doesn’t need to know which handler will process the request.</em></strong></blockquote><p>It simply sends the request into the chain.</p><p>That’s the core idea behind the <strong>Chain of Responsibility Design Pattern</strong>.</p><h3>What is the Chain of Responsibility Pattern?</h3><p>The textbook definition is:</p><blockquote><strong><em>“Chain of Responsibility passes a request along a chain of handlers until one of them handles it.”</em></strong></blockquote><p>In simple words:</p><blockquote><strong><em>Send a request to the first handler and let each handler decide whether to process it or pass it to the next handler.</em></strong></blockquote><p>The structure looks like this:</p><pre>Client<br>   ↓<br>Handler 1<br>   ↓<br>Handler 2<br>   ↓<br>Handler 3</pre><p>Each handler knows only about the <strong>next handler</strong>, not the entire chain.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/339/0*cOVGOQA_yATuut9a" /></figure><h3>Why Do We Need It?</h3><p>Suppose we are building a logging system.</p><p>We have three log levels:</p><pre>INFO<br>DEBUG<br>ERROR</pre><p>We could write:</p><pre>if (level == INFO) {<br>    // handle info<br>} else if (level == DEBUG) {<br>    // handle debug<br>} else if (level == ERROR) {<br>    // handle error<br>}</pre><p>As the number of handlers grows, this logic can become difficult to maintain.</p><p>Instead, we can create a chain:</p><pre>InfoLogger<br>    ↓<br>DebugLogger<br>    ↓<br>ErrorLogger</pre><p>Now the client simply sends the request to the beginning of the chain.</p><h3>The Core Idea</h3><p>Every handler has two responsibilities:</p><ol><li><strong>Try to handle the request</strong></li><li><strong>If it cannot, pass it to the next handler</strong></li></ol><p>Conceptually:</p><pre>handle(request)<br><br>Can I handle it?<br>       /     \<br>     Yes      No<br>      ↓        ↓<br>   Handle   Next Handler</pre><p>This is why the pattern is called <strong>Chain of Responsibility</strong>.</p><p>The responsibility for handling a request is distributed across a chain of objects.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/425/0*RaUaqwmUKsh7wRNm" /></figure><h3>Let’s Build It</h3><p>First, create a common handler:</p><pre>abstract class LogProcessor {<br>    protected LogProcessor nextProcessor;<br>    public LogProcessor(LogProcessor nextProcessor) {<br>        this.nextProcessor = nextProcessor;<br>    }<br>    public abstract void log(String level, String message);<br>}</pre><p>Each processor can now have a reference to the next processor.</p><h3>Info Processor</h3><pre>class InfoLogProcessor extends LogProcessor {<br><br>    public InfoLogProcessor(LogProcessor nextProcessor) {<br>        super(nextProcessor);<br>    }<br><br>    @Override<br>    public void log(String level, String message) {<br>        if (level.equals(&quot;INFO&quot;)) {<br>            System.out.println(&quot;INFO: &quot; + message);<br>        } else if (nextProcessor != null) {<br>            nextProcessor.log(level, message);<br>        }<br>    }<br>}</pre><p>If it cannot handle the request, it forwards it.</p><h3>Debug Processor</h3><pre>class DebugLogProcessor extends LogProcessor {<br><br>    public DebugLogProcessor(LogProcessor nextProcessor) {<br>        super(nextProcessor);<br>    }<br><br>    @Override<br>    public void log(String level, String message) {<br>        if (level.equals(&quot;DEBUG&quot;)) {<br>            System.out.println(&quot;DEBUG: &quot; + message);<br>        } else if (nextProcessor != null) {<br>            nextProcessor.log(level, message);<br>        }<br>    }<br>}</pre><h3>Error Processor</h3><pre>class ErrorLogProcessor extends LogProcessor {<br><br>    public ErrorLogProcessor(LogProcessor nextProcessor) {<br>        super(nextProcessor);<br>    }<br><br>    @Override<br>    public void log(String level, String message) {<br>        if (level.equals(&quot;ERROR&quot;)) {<br>            System.out.println(&quot;ERROR: &quot; + message);<br>        } else if (nextProcessor != null) {<br>            nextProcessor.log(level, message);<br>        }<br>    }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/335/0*L1T-RAgjl1crhK4R" /></figure><h3>Creating the Chain</h3><p>Now we connect them:</p><pre>LogProcessor error =<br>        new ErrorLogProcessor(null);<br><br>LogProcessor debug =<br>        new DebugLogProcessor(error);<br><br>LogProcessor info =<br>        new InfoLogProcessor(debug);</pre><p>The chain is:</p><pre>InfoLogProcessor<br>       ↓<br>DebugLogProcessor<br>       ↓<br>ErrorLogProcessor<br>       ↓<br>     null</pre><p>The client only needs to know about the <strong>first handler</strong>:</p><pre>info.log(&quot;ERROR&quot;, &quot;Database connection failed&quot;);</pre><p>The request travels through the chain:</p><pre>Client<br>  ↓<br>Info<br>  ↓<br>Debug<br>  ↓<br>Error<br>  ↓<br>Handles request</pre><p>The client doesn’t know that ErrorLogProcessor will ultimately handle it.</p><h3>A Very Important Point</h3><p>The client should <strong>not</strong> decide which handler processes the request.</p><p>That’s the responsibility of the chain.</p><p>Instead of:</p><pre>Client → &quot;If ERROR, call ErrorProcessor&quot;</pre><p>we want:</p><pre>Client → First Handler<br>              ↓<br>          Can you handle?<br>           ↓       ↓<br>         Yes       No<br>          ↓         ↓<br>       Handle    Next Handler</pre><p>This keeps the client independent of the concrete handlers.</p><h3>Remember the ATM?</h3><p>The ATM example from the beginning is exactly the same idea in the real world.</p><p>A withdrawal request enters the chain, and each handler checks whether it can fulfill the request. If it can’t, the request moves to the next handler.</p><p>The customer simply asks for the withdrawal — they don’t need to know which handler will ultimately fulfill it.</p><h3>What If Nobody Can Handle It?</h3><p>A chain can reach its end without processing the request.</p><p>For example, imagine the ATM needs to dispense ₹100 notes, but no suitable handler can fulfill the remaining amount.</p><p>The chain might end like this:</p><pre>₹2000 Handler<br>      ↓<br>₹500 Handler<br>      ↓<br>₹100 Handler<br>      ↓<br>    null</pre><p>At that point, the system needs a defined fallback behavior:</p><ul><li>reject the request</li><li>return a failure</li><li>throw an exception</li><li>use a default handler</li></ul><p>For example:</p><pre>if (nextProcessor != null) {<br>    nextProcessor.log(level, message);<br>} else {<br>    System.out.println(&quot;No handler found&quot;);<br>}</pre><p>So <strong>Chain of Responsibility does not guarantee that a request will be handled</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/365/0*fqB0uoE2TLkuvaHd" /></figure><h3>The Three Main Parts</h3><h3>1. Client</h3><p>Creates or sends the request.</p><pre>Client → Handler</pre><h3>2. Handler</h3><p>Defines the common way handlers process requests and keeps a reference to the next handler.</p><pre>Handler<br> ├── handle(request)<br> └── nextHandler</pre><h3>3. Concrete Handlers</h3><p>Actually decide whether they can handle the request.</p><pre>Handler<br>   ↓<br>InfoHandler<br>   ↓<br>DebugHandler<br>   ↓<br>ErrorHandler</pre><h3>When Should You Use It?</h3><p>Use Chain of Responsibility when:</p><ul><li>Multiple objects could handle the same request.</li><li>The sender shouldn’t know which object will handle it.</li><li>You want to dynamically change the chain.</li><li>You want to avoid large if-else or switch logic.</li><li>Processing should move through multiple possible handlers.</li></ul><p>Common examples:</p><pre>Logging systems<br>ATM withdrawal<br>Authentication / authorization checks<br>Exception handling<br>Middleware<br>Approval workflows</pre><p>For example:</p><pre>Authentication<br>      ↓<br>Authorization<br>      ↓<br>Validation<br>      ↓<br>Rate Limiting<br>      ↓<br>Request Handler</pre><p>Each component can decide whether to process/reject the request or pass it forward.</p><h3>Chain of Responsibility vs Similar Patterns</h3><p>These patterns can sometimes look similar because they involve passing requests or delegating work. The key difference is <strong>what happens to the request</strong>:</p><p><strong>Chain of Responsibility</strong> → Passes the request through handlers until one handles it<br> <strong>Observer</strong> → Notifies multiple interested objects about a change<br> <strong>Decorator</strong> → Adds behavior by wrapping an object<br> <strong>Command</strong> → Encapsulates a request as an object</p><p>The most important distinction is with <strong>Observer</strong>.</p><h3>Chain of Responsibility</h3><pre>Request<br>  ↓<br>Handler A<br>  ↓<br>Handler B<br>  ↓<br>Handler C</pre><p>The request moves <strong>forward until it is handled</strong>.</p><h3>Observer</h3><pre>Event<br> ├──→ Observer A<br> ├──→ Observer B<br> └──→ Observer C</pre><p>The subject <strong>notifies multiple observers</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/637/0*faneESwZVNtAAhp8" /></figure><h3>Final Mental Model</h3><p>Think of a chain of people handling a customer request:</p><pre>Customer<br>   ↓<br>Employee 1<br>   ↓<br>Employee 2<br>   ↓<br>Manager</pre><p>Each person asks:</p><blockquote><strong><em>“Can I handle this?”</em></strong></blockquote><p>If yes → handle it.</p><p>If no → pass it to the next person.</p><p>That’s <strong>Chain of Responsibility</strong>.</p><blockquote><strong><em>One request + multiple possible handlers + a linked chain = Chain of Responsibility.</em></strong></blockquote><p>The sender doesn’t need to know <strong>who</strong> will handle the request.</p><p>It only needs to know <strong>where to start the chain</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/373/0*iRHQJrfweqn95Nve" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=53728f6b02a5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Template Method Design Pattern — Define the Algorithm, Let Subclasses Fill the Gaps]]></title>
            <link>https://medium.com/@AdvanceQuest_/template-method-design-pattern-define-the-algorithm-let-subclasses-fill-the-gaps-ff6d5b300ee7?source=rss-f1ae2fdec112------2</link>
            <guid isPermaLink="false">https://medium.com/p/ff6d5b300ee7</guid>
            <dc:creator><![CDATA[Hruday⚡️]]></dc:creator>
            <pubDate>Mon, 07 Sep 2026 14:52:25 GMT</pubDate>
            <atom:updated>2026-09-07T14:52:25.035Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oGkHKgGpHGIkEGO7qE7FmA.png" /></figure><p>Imagine you’re building a system that generates different types of reports.</p><p>A <strong>User Report</strong> and a <strong>Sales Report</strong> are different, but the overall process is the same:</p><pre>Validate<br>   ↓<br>Fetch Data<br>   ↓<br>Generate Report<br>   ↓<br>Notify<br>   ↓<br>Save</pre><p>The workflow should remain the same, while individual steps can vary.</p><p>That’s where the <strong>Template Method Pattern</strong> comes in.</p><h3>What Is the Template Method Pattern?</h3><p>The classic definition is:</p><blockquote><strong><em>“Define the skeleton of an algorithm in an operation, deferring some steps to subclasses.”</em></strong></blockquote><p>In simple terms:</p><blockquote><strong><em>Define the algorithm once, keep its structure fixed, and let subclasses customize specific steps.</em></strong></blockquote><h3>The Problem</h3><p>Without Template Method, we might duplicate the workflow:</p><pre>class UserReport {<br>    void generate() {<br>        validate();<br>        fetchData();<br>        generateReport();<br>        notifyUser();<br>        save();<br>    }<br>}</pre><p>And again:</p><pre>class SalesReport {<br>    void generate() {<br>        validate();<br>        fetchData();<br>        generateReport();<br>        notifyUser();<br>        save();<br>    }<br>}</pre><p>The workflow is duplicated.</p><p>But there’s another, more important problem: <strong>the order of these steps matters</strong>.</p><p>Someone could accidentally implement another report like this:</p><pre>Save<br>  ↓<br>Validate<br>  ↓<br>Fetch Data</pre><p>The classes should be free to customize <strong>individual steps</strong>, but they shouldn’t accidentally change the <strong>overall algorithm</strong>.</p><h3>The Core Idea</h3><p>Create a base class that owns the algorithm.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/584/0*btC5yLBpZeZeZK3q" /></figure><p>The base class decides <strong>what happens and in what order</strong>.</p><p>The subclasses decide <strong>how specific steps happen</strong>.</p><h3>Java Example</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/319/0*affIaceGoqr0VVaG" /></figure><pre>abstract class Report {<br>    public final void generate() {<br>        validate();<br>        fetchData();<br>        generateReport();<br>        if (shouldNotify()) {<br>            notifyUser();<br>        }<br>        save();<br>    }<br>    // Abstract operations<br>    protected abstract void fetchData();<br>    protected abstract void generateReport();<br>    // Concrete operations<br>    protected void validate() {<br>        System.out.println(&quot;Common validation&quot;);<br>    }<br>    protected void save() {<br>        System.out.println(&quot;Saving report&quot;);<br>    }<br>    protected void notifyUser() {<br>        System.out.println(&quot;Notification sent&quot;);<br>    }<br>    // Hook<br>    protected boolean shouldNotify() {<br>        return true;<br>    }<br>}</pre><p>A specific report provides the variable steps:</p><pre>class UserReport extends Report {<br>    @Override<br>    protected void fetchData() {<br>        System.out.println(&quot;Fetching user data&quot;);<br>    }<br>    @Override<br>    protected void generateReport() {<br>        System.out.println(&quot;Generating user report&quot;);<br>    }<br>}</pre><p>And a report that doesn’t need notifications can customize the hook:</p><pre>class SilentReport extends Report {<br>    @Override<br>    protected void fetchData() {<br>        System.out.println(&quot;Fetching data&quot;);<br>    }<br>    @Override<br>    protected void generateReport() {<br>        System.out.println(&quot;Generating report&quot;);<br>    }<br>    @Override<br>    protected boolean shouldNotify() {<br>        return false;<br>    }<br>}</pre><p>Usage:</p><pre>Report report = new UserReport();<br>report.generate();</pre><p>The execution is:</p><pre>generate()<br>   │<br>   ├── validate()<br>   ├── fetchData()       → UserReport<br>   ├── generateReport()  → UserReport<br>   ├── shouldNotify()<br>   ├── notifyUser()<br>   └── save()</pre><p>The important part is that UserReport <strong>doesn&#39;t control the order</strong>. The base class does.</p><h3>Three Types of Methods</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/534/0*wqUfljQLs7B02I_C" /></figure><h3>1. Concrete Operation</h3><p>Common implementation provided by the base class.</p><pre>protected void save() {<br>    System.out.println(&quot;Saving report&quot;);<br>}</pre><h3>2. Abstract Operation</h3><p>Subclass must provide the implementation.</p><pre>protected abstract void fetchData();</pre><h3>3. Hook</h3><p>An optional customization point.</p><pre>protected boolean shouldNotify() {<br>    return true;<br>}</pre><p>A subclass can override it when necessary, like SilentReport.</p><p>So remember:</p><pre>Concrete Operation → Common implementation<br>Abstract Operation → Required customization<br>Hook              → Optional customization</pre><h3>Why final?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/446/1*0r2iZzSqHwjX4Bwes-DIIQ.png" /></figure><p>The Template Method is often declared as:</p><pre>public final void generate()</pre><p>This prevents subclasses from changing the algorithm itself.</p><p>The subclass can change:</p><blockquote><strong><em>HOW a step works</em></strong></blockquote><p>but not:</p><blockquote><strong><em>WHICH step comes first</em></strong></blockquote><p>So the workflow stays:</p><pre>Validate<br>   ↓<br>Fetch Data<br>   ↓<br>Generate Report<br>   ↓<br>Notify<br>   ↓<br>Save</pre><h3>The Hollywood Principle</h3><p>Template Method is closely related to the <strong>Hollywood Principle</strong>:</p><blockquote><strong><em>“Don’t call us, we’ll call you.”</em></strong></blockquote><p>The base class controls the workflow and calls subclass methods when needed.</p><pre>Base Class<br>    │<br>    ├── Common methods<br>    │<br>    └── Subclass-specific methods</pre><h3>Template Method vs Strategy Pattern</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/681/0*wshlSQc06ibs2lsn" /></figure><h3>Template Method</h3><p>Uses <strong>inheritance</strong>.</p><pre>        Report<br>          │<br>     ┌────┴────┐<br>     ↓         ↓<br>  User       Sales</pre><p>Same algorithm, different steps.</p><h3>Strategy Pattern</h3><p>Uses <strong>composition</strong>.</p><pre>        Report<br>          │<br>          ↓<br>       Strategy<br>       /      \<br>      ↓        ↓<br> Strategy A  Strategy B</pre><p>Different behaviors can be swapped independently.</p><p><strong>Easy way to remember:</strong></p><blockquote><strong><em>Template Method → Same algorithm, different steps.</em></strong></blockquote><blockquote><strong><em>Strategy → Different algorithms/behaviors, interchangeable objects.</em></strong></blockquote><h3>When Should You Use It?</h3><p>Use Template Method when:</p><ul><li>Multiple classes follow the <strong>same overall algorithm</strong></li><li>The <strong>order of steps must remain consistent</strong></li><li>Some steps vary between implementations</li><li>You want to avoid duplicating the workflow</li></ul><p>Examples include:</p><pre>Report generation<br>File processing<br>Data import<br>Document generation<br>Request processing</pre><h3>Trade-off</h3><p>Template Method relies on <strong>inheritance</strong>, so subclasses are coupled to the base class.</p><p>If behavior needs to be freely swapped or combined, <strong>Strategy</strong> may be a better choice.</p><h3>Final Mental Model</h3><p>Think of generate() as a <strong>recipe for creating a report</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/532/0*n-FzTGb4gGc0Ha5S" /></figure><blockquote><strong><em>Template Method = Fixed algorithm + customizable steps.</em></strong></blockquote><p>The base class controls <strong>the recipe</strong>.</p><p>The subclasses provide <strong>the variable parts</strong>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ff6d5b300ee7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Adapter Design Pattern — Make Incompatible Code Work Together]]></title>
            <link>https://medium.com/@AdvanceQuest_/adapter-design-pattern-make-incompatible-code-work-together-a2d17a5759d5?source=rss-f1ae2fdec112------2</link>
            <guid isPermaLink="false">https://medium.com/p/a2d17a5759d5</guid>
            <dc:creator><![CDATA[Hruday⚡️]]></dc:creator>
            <pubDate>Sun, 06 Sep 2026 11:09:56 GMT</pubDate>
            <atom:updated>2026-09-06T11:09:56.879Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7FxVgMdSl3MHQx6PlJjWkw.png" /></figure><p>Imagine you have a charger designed for an <strong>Indian socket</strong>, but the wall socket in your hotel room is <strong>US-style</strong>.</p><p>The charger and socket don’t match.</p><p>You don’t change either one.</p><p>You use an <strong>Adapter</strong>.</p><pre>Indian Charger<br>      ↓<br>   Adapter<br>      ↓<br>  US Socket</pre><p>The same idea exists in software.</p><p>Sometimes two classes need to work together, but their interfaces don’t match.</p><p>Instead of changing existing code, we introduce an <strong>Adapter</strong> between them.</p><blockquote><strong><em>Adapter Pattern converts the interface of a class into another interface that clients expect.</em></strong></blockquote><h3>Why Do We Need It?</h3><p>Suppose our application expects a notification service like this:</p><pre>interface NotificationService {<br>    void send(String message);<br>}</pre><p>Our application simply does:</p><pre>service.send(&quot;Payment successful&quot;);</pre><p>Now imagine we integrate a third-party notification library.</p><p>Its API looks completely different:</p><pre>class ThirdPartyNotifier {<br>    public void sendNotification(String text) {<br>        System.out.println(&quot;Sending: &quot; + text);<br>    }<br>}</pre><p>Our application expects:</p><pre>send(message)</pre><p>But the third-party library provides:</p><pre>sendNotification(text)</pre><p>They don’t match.</p><p>We could change our application to use sendNotification() everywhere.</p><p>But now our application is tightly coupled to that third-party library.</p><p>Instead:</p><pre>Our Application<br>      ↓<br>   Adapter<br>      ↓<br>Third-Party Library</pre><p>The Adapter translates between the two interfaces.</p><h3>Target, Adaptee, and Adapter</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/285/0*iWOkerp8MZibo9bU" /></figure><p>There are three important parts.</p><h3>Target</h3><p>The interface that <strong>our client expects</strong>.</p><pre>interface NotificationService {<br>    void send(String message);<br>}</pre><h3>Adaptee</h3><p>The existing class that we want to use, but whose interface doesn’t match.</p><pre>class ThirdPartyNotifier {<br>    public void sendNotification(String text) {<br>        System.out.println(&quot;Sending: &quot; + text);<br>    }<br>}</pre><h3>Adapter</h3><p>The class that makes the Adaptee work through the Target interface.</p><p>Think of it like a language translator:</p><pre>Client<br>  ↓<br>Adapter<br>  ↓<br>Third-Party Library</pre><p>The client speaks the language of NotificationService.</p><p>The third-party library speaks a different language.</p><p>The Adapter translates between them.</p><h3>How Does the Adapter Fit In?</h3><p>Here’s the important part.</p><p>The Adapter <strong>is a </strong><strong>NotificationService</strong>:</p><pre>class NotificationAdapter implements NotificationService {</pre><p>So:</p><pre>NotificationAdapter IS-A NotificationService</pre><p>At the same time, it <strong>has a </strong><strong>ThirdPartyNotifier</strong>:</p><pre>private final ThirdPartyNotifier notifier;</pre><p>So:</p><pre>NotificationAdapter HAS-A ThirdPartyNotifier</pre><p>This gives us:</p><blockquote><strong><em>IS-A Target + HAS-A Adaptee</em></strong></blockquote><p>The Adapter can therefore be used anywhere the client expects a NotificationService.</p><p>And most importantly:</p><blockquote><strong><em>The client depends only on </em></strong><strong><em>NotificationService, never directly on </em></strong><strong><em>ThirdPartyNotifier.</em></strong></blockquote><p>That’s what keeps the third-party implementation isolated from the rest of the application.</p><h3>Simple Java Example</h3><p>Let’s create the Adapter:</p><pre>class NotificationAdapter implements NotificationService {<br>    private final ThirdPartyNotifier notifier;<br>    public NotificationAdapter(ThirdPartyNotifier notifier) {<br>        this.notifier = notifier;<br>    }<br>    @Override<br>    public void send(String message) {<br>        notifier.sendNotification(message);<br>    }<br>}</pre><p>Now the client can use it normally:</p><pre>NotificationService service =<br>        new NotificationAdapter(<br>            new ThirdPartyNotifier()<br>        );<br>service.send(&quot;Payment successful&quot;);</pre><p>What happens internally?</p><pre>Client<br>  ↓<br>send(&quot;Payment successful&quot;)<br>  ↓<br>NotificationAdapter<br>  ↓<br>sendNotification(&quot;Payment successful&quot;)<br>  ↓<br>ThirdPartyNotifier</pre><p>The Adapter has translated:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/402/0*ilknddYnCGJ18-h5" /></figure><p>The third-party class remains unchanged.</p><p>The client remains unchanged.</p><p>Only the Adapter knows how to connect them.</p><h3>Object Adapter vs Class Adapter</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/334/0*2wMpsmQHyBvPAcb2" /></figure><p>There are two forms of Adapter.</p><h3>Object Adapter</h3><p>Uses <strong>composition</strong>:</p><pre>Adapter<br>   ↓<br>Adaptee</pre><p>In Java:</p><pre>class Adapter implements Target {<br>    private final Adaptee adaptee;<br>    // ...<br>}</pre><p>This is the approach we used above.</p><p>It follows:</p><blockquote><strong><em>Favor composition over inheritance.</em></strong></blockquote><h3>Class Adapter</h3><p>Uses <strong>inheritance</strong>:</p><pre>Target<br>  ↑<br>Adapter<br>  ↑<br>Adaptee</pre><p>Conceptually, the Adapter inherits from both the Target and Adaptee.</p><p>This requires <strong>multiple inheritance</strong>.</p><p>Java doesn’t support multiple inheritance of classes, so this approach isn’t directly available for Java classes.</p><p>Languages such as C++ can support it, but even there, composition is often preferred because it provides more flexibility.</p><p>So remember:</p><blockquote><strong><em>Object Adapter → Composition</em></strong></blockquote><blockquote><strong><em>Class Adapter → Inheritance</em></strong></blockquote><h3>Adapter vs Decorator vs Proxy</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/920/0*1jD2c3i1Bb_WPck0" /></figure><p>These patterns can look similar because all of them can wrap objects.</p><p>But their <strong>intent</strong> is different.</p><h3>Adapter</h3><blockquote><strong><em>Makes incompatible interfaces work together.</em></strong></blockquote><pre>Client → Adapter → Adaptee</pre><h3>Decorator</h3><blockquote><strong><em>Adds additional behavior.</em></strong></blockquote><pre>Client → Decorator → Object</pre><h3>Proxy</h3><blockquote><strong><em>Controls access to an object.</em></strong></blockquote><pre>Client → Proxy → Real Object</pre><p>A simple mental model:</p><pre>Adapter   → &quot;Make these two things compatible.&quot;<br>Decorator → &quot;Add more behavior.&quot;<br>Proxy     → &quot;Control access.&quot;</pre><h3>Real-World Use Cases</h3><h3>1. Third-Party Libraries</h3><p>Your application has its own interface, while an external library has a different API.</p><pre>Application<br>     ↓<br>  Adapter<br>     ↓<br>Third-Party Library</pre><p>Examples:</p><ul><li>payment providers</li><li>notification providers</li><li>analytics SDKs</li><li>external APIs</li></ul><p>You keep vendor-specific code inside the Adapter.</p><h3>2. Legacy Code</h3><p>Your modern application needs to work with an older system.</p><pre>Modern Application<br>       ↓<br>     Adapter<br>       ↓<br>   Legacy System</pre><p>Instead of rewriting the old system, the Adapter translates your application’s calls into the format the legacy code understands.</p><h3>3. Multiple Providers</h3><p>Suppose your application supports multiple notification providers:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/558/0*zdACJS4duq-EKlRk" /></figure><p>Each provider can have its own Adapter.</p><p>Your application still works with:</p><pre>NotificationService</pre><p>It doesn’t need to know which provider is underneath.</p><h3>When to Use Adapter</h3><p>Use Adapter when:</p><ul><li>an existing class has an incompatible interface</li><li>you need to integrate a third-party library</li><li>you need to work with legacy code</li><li>you want to isolate external/vendor-specific code</li><li>you want your application to depend on a stable interface instead of an external API</li></ul><h3>Adapter Pattern in One Picture</h3><pre>┌──────────────┐<br>│    Client    │<br>└──────┬───────┘<br>       │<br>       ↓<br>┌──────────────┐<br>│    Target    │<br>│   Interface  │<br>└──────┬───────┘<br>       │<br>       ↓<br>┌──────────────┐<br>│   Adapter    │<br>│  Translates  │<br>└──────┬───────┘<br>       │<br>       ↓<br>┌──────────────┐<br>│   Adaptee    │<br>│ Existing API │<br>└──────────────┘</pre><h3>Remember It Like This</h3><blockquote><strong><em>Adapter = Make incompatible interfaces work together without changing the existing classes.</em></strong></blockquote><pre>Client<br>  ↓<br>Target<br>  ↓<br>Adapter<br>  ↓<br>Adaptee</pre><p><strong>Different interfaces + translation + composition = Adapter.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a2d17a5759d5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Decorator Design Pattern — Add Behavior Without Changing the Object]]></title>
            <link>https://medium.com/@AdvanceQuest_/decorator-design-pattern-add-behavior-without-changing-the-object-65dbefe45dd4?source=rss-f1ae2fdec112------2</link>
            <guid isPermaLink="false">https://medium.com/p/65dbefe45dd4</guid>
            <dc:creator><![CDATA[Hruday⚡️]]></dc:creator>
            <pubDate>Sun, 06 Sep 2026 10:10:42 GMT</pubDate>
            <atom:updated>2026-09-06T10:10:42.435Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*olawRPlxVUKjtMFSir2Jwg.png" /></figure><p>Imagine you already have an object that works perfectly.</p><p>Now you want to add some extra behavior <strong>without modifying its class</strong>.</p><p>Instead of creating more and more subclasses, we can <strong>wrap the object with a Decorator</strong>.</p><blockquote><strong><em>Decorator Pattern attaches additional responsibilities to an object dynamically.</em></strong></blockquote><p>The basic idea:</p><pre>Client<br>  ↓<br>Decorator<br>  ↓<br>Real Object</pre><p>And decorators can be stacked:</p><pre>Client<br>  ↓<br>Decorator B<br>  ↓<br>Decorator A<br>  ↓<br>Real Object</pre><h3>Why Do We Need It?</h3><p>Suppose we have a notification system:</p><pre>EmailNotifier</pre><p>Now we want to support:</p><ul><li>SMS</li><li>Push notification</li><li>Logging</li></ul><p>With inheritance, we may start creating combinations:</p><pre>EmailNotifier<br> ├── EmailWithSms<br> ├── EmailWithPush<br> ├── EmailWithSmsAndPush<br> ├── EmailWithSmsAndLogging<br> ├── EmailWithPushAndLogging<br> └── ... and many more combinations</pre><p>As the number of behaviors grows, the number of combinations can grow rapidly.</p><p>Instead, we can compose them:</p><pre>EmailNotifier<br>     ↓<br>SmsDecorator<br>     ↓<br>PushDecorator<br>     ↓<br>LoggingDecorator</pre><p>No separate class is required for every combination.</p><h3>The Most Important Part</h3><p>A Decorator generally:</p><ul><li>implements the same Component abstraction (IS-A)</li><li>contains a reference to that Component (HAS-A)</li><li>delegates to the wrapped object</li><li>adds its own behavior</li></ul><p>So the key idea is:</p><blockquote><strong><em>IS-A Component + HAS-A Component</em></strong></blockquote><p>For our example:</p><pre>Notifier<br>├── EmailNotifier<br>└── Decorator</pre><p>The Decorator is also a Notifier, and it contains another Notifier.</p><p>Because of this, the client doesn’t care whether it is using the original object or a decorated one.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/406/0*vKrJ6xS4_gSEuLmH" /></figure><h3>Simple Java Example</h3><p>First, define the common interface:</p><pre>interface Notifier {<br>    void send(String message);<br>}</pre><h3>Real Object</h3><pre>class EmailNotifier implements Notifier {<br>    @Override<br>    public void send(String message) {<br>        System.out.println(&quot;Sending Email: &quot; + message);<br>    }<br>}</pre><p>Now create a decorator:</p><pre>class SmsDecorator implements Notifier {<br>    private final Notifier notifier;<br>    public SmsDecorator(Notifier notifier) {<br>        this.notifier = notifier;<br>    }<br>    @Override<br>    public void send(String message) {<br>        notifier.send(message);<br>        System.out.println(&quot;Sending SMS: &quot; + message);<br>    }<br>}</pre><p>Notice what happened.</p><p>The decorator:</p><ol><li>receives a Notifier</li><li>calls the wrapped object’s send()</li><li>adds its own behavior</li></ol><p>Now compose them:</p><pre>Notifier notifier = <br>            new SmsDecorator(<br>                new EmailNotifier()<br>            );<br>notifier.send(&quot;Payment successful&quot;);</pre><p>Output:</p><pre>Sending Email: Payment successful<br>Sending SMS: Payment successful</pre><p>The original EmailNotifier was never changed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/321/0*9G0w4e5MRsbsxBSk" /></figure><h3>Multiple Decorators</h3><p>Now let’s add Push notifications.</p><pre>class PushDecorator implements Notifier {<br>    private final Notifier notifier;<br>    public PushDecorator(Notifier notifier) {<br>        this.notifier = notifier;<br>    }<br>    @Override<br>    public void send(String message) {<br>        notifier.send(message);<br>        System.out.println(&quot;Sending Push: &quot; + message);<br>    }<br>}</pre><p>We can now stack decorators:</p><pre>Notifier notifier =<br>        new PushDecorator(<br>            new SmsDecorator(<br>                new EmailNotifier()<br>            )<br>        );</pre><p>The structure is:</p><h3>Call order — going down</h3><pre>PushDecorator<br>      ↓<br>SmsDecorator<br>      ↓<br>EmailNotifier</pre><p>When the client calls:</p><pre>notifier.send(&quot;Payment successful&quot;);</pre><p>PushDecorator receives the call first.</p><p>It delegates to SmsDecorator.</p><p>SmsDecorator delegates to EmailNotifier.</p><p>EmailNotifier performs the original behavior.</p><h3>Output order — coming back up</h3><pre>EmailNotifier<br>      ↑<br>SmsDecorator   → SMS added<br>      ↑<br>PushDecorator  → Push added</pre><p>So the output is:</p><pre>Sending Email: Payment successful<br>Sending SMS: Payment successful<br>Sending Push: Payment successful</pre><p>This is one of the most important things to understand about Decorators:</p><blockquote><strong><em>The call travels from the outermost decorator inward, while the added behavior can appear as the call unwinds outward.</em></strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/551/0*3XlsiFaENsz8S9Z8" /></figure><h3>Decorator vs Proxy</h3><p>Both patterns wrap objects, so they can look very similar.</p><p>But their <strong>intent</strong> is different.</p><h3>Proxy</h3><blockquote><strong><em>Controls access to an object.</em></strong></blockquote><pre>Client → Proxy → Real Object</pre><p>Examples:</p><ul><li>lazy creation</li><li>permission checks</li><li>remote access</li></ul><h3>Decorator</h3><blockquote><strong><em>Adds behavior to an object.</em></strong></blockquote><pre>Client → Decorator → Object</pre><p>Examples:</p><ul><li>logging</li><li>notifications</li><li>buffering</li><li>additional processing</li></ul><p>A simple way to remember:</p><blockquote><strong><em>Proxy → “How should this object be accessed?”</em></strong></blockquote><blockquote><strong><em>Decorator → “What additional behavior should this object have?”</em></strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/563/0*Wrj94CzBf3F495-s" /></figure><h3>A Real-World Example</h3><p>Java I/O makes extensive use of this wrapping style:</p><pre>FileInputStream<br>      ↓<br>BufferedInputStream<br>      ↓<br>Another Wrapper</pre><p>Each wrapper adds behavior while still behaving like an InputStream.</p><p>This is Decorator in production code, not just a design-pattern example.</p><h3>When to Use Decorator</h3><p>Use Decorator when:</p><ul><li>you need to add behavior dynamically</li><li>multiple behaviors can be combined</li><li>subclassing would create too many combinations</li><li>you want to extend behavior without modifying the original class</li></ul><h3>Decorator Pattern in One Picture</h3><pre>┌──────────────┐<br>│    Client    │<br>└──────┬───────┘<br>       ↓<br>┌──────────────┐<br>│  Decorator B │<br>│ Add Behavior │<br>└──────┬───────┘<br>       ↓<br>┌──────────────┐<br>│  Decorator A │<br>│ Add Behavior │<br>└──────┬───────┘<br>       ↓<br>┌──────────────┐<br>│  Real Object │<br>│ Core Behavior│<br>└──────────────┘</pre><h3>Remember It Like This</h3><blockquote><strong><em>Decorator = Wrap an object to add behavior dynamically while keeping the same Component abstraction.</em></strong></blockquote><pre>Object<br>  ↓<br>Decorator<br>  ↓<br>Decorator</pre><p><strong>Same abstraction + wrapping + composition = Decorator.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=65dbefe45dd4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Proxy Design Pattern — Control Access Without Changing the Interface]]></title>
            <link>https://medium.com/@AdvanceQuest_/proxy-design-pattern-control-access-without-changing-the-interface-ab6ccccfd66c?source=rss-f1ae2fdec112------2</link>
            <guid isPermaLink="false">https://medium.com/p/ab6ccccfd66c</guid>
            <dc:creator><![CDATA[Hruday⚡️]]></dc:creator>
            <pubDate>Thu, 03 Sep 2026 19:21:12 GMT</pubDate>
            <atom:updated>2026-09-03T19:21:12.826Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NMRN27ScsYcFBm0OhjP9jA.png" /></figure><p>Imagine you want to access an object.</p><p>Instead of talking to that object directly, you talk to a <strong>Proxy</strong>.</p><p>The Proxy stands in front of the real object and decides <strong>how and when the real object should be accessed</strong>.</p><blockquote><strong><em>Proxy Pattern provides a surrogate or placeholder for another object to control access to it.</em></strong></blockquote><h3>The Basic Idea</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/274/0*3zrMq3L3QVczCMGh" /></figure><p>Without a Proxy:</p><pre>Client ───────────────&gt; Real Object</pre><p>With a Proxy:</p><pre>Client ──&gt; Proxy ──&gt; Real Object</pre><p>The client works with the Proxy as if it were the real object.</p><p>The Proxy gets a chance to control access before the real object is used.</p><h3>Why Do We Need It?</h3><p>Sometimes accessing or creating an object isn’t something we want to do immediately.</p><p>For example:</p><ul><li>The object is <strong>expensive to create</strong></li><li>The object exists on a <strong>remote server</strong></li><li>Only certain users should access it</li><li>We want to <strong>delay the actual work</strong> until it’s needed</li></ul><p>Instead of putting all this logic into the real object, we can put a Proxy in front of it.</p><h3>The Most Important Part: Same Interface</h3><p>A Proxy generally implements the <strong>same interface as the real object</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/608/0*_BXtybyRL_2YrVNS" /></figure><p>Both implement:</p><pre>interface BookParser {<br>    int getNumberOfPages();<br>}</pre><p>So the client doesn’t need to know whether it’s talking to the real object or its Proxy.</p><pre>Client<br>  ↓<br>BookParser interface<br>  ↓<br>Proxy<br>  ↓<br>RealBookParser</pre><p>This is what makes the Proxy transparent to the client.</p><h3>Three Common Types</h3><p><strong>1. Virtual Proxy</strong><br> Delays the creation of an expensive object until it is actually needed.</p><p><strong>2. Remote Proxy</strong><br> Represents and accesses an object that exists on a remote system.</p><p><strong>3. Protection Proxy</strong><br> Controls access to an object based on permissions.</p><h3>1. Virtual Proxy — Create Expensive Objects Only When Needed</h3><p>Imagine we have a BookParser.</p><p>Creating it performs expensive parsing:</p><pre>BookParser parser = new RealBookParser(hugeBook);</pre><p>But what if the application creates the parser and never actually uses it?</p><p>That’s wasted work.</p><h3>Without Proxy</h3><pre>Create BookParser<br>       ↓<br>Expensive parsing happens<br>       ↓<br>Maybe we use it<br>       ↓<br>Maybe we don&#39;t</pre><h3>With Proxy</h3><pre>Create Proxy<br>       ↓<br>Nothing expensive happens<br>       ↓<br>Someone actually needs the data<br>       ↓<br>Create RealBookParser<br>       ↓<br>Perform expensive parsing</pre><p>This is called a <strong>Virtual Proxy</strong>.</p><blockquote><em>A Virtual Proxy delays the creation of an expensive object until it is actually needed.</em></blockquote><h3>Example</h3><p>First, define the common interface:</p><pre>interface BookParser {<br>    int getNumberOfPages();<br>}</pre><p>The real object performs the expensive work:</p><pre>class RealBookParser implements BookParser {<br>    public RealBookParser(String book) {<br>        System.out.println(&quot;Parsing huge book...&quot;);<br>        // Expensive parsing<br>    }<br>    @Override<br>    public int getNumberOfPages() {<br>        return 300;<br>    }<br>}</pre><p>Now the Proxy:</p><pre>class LazyBookParser implements BookParser {<br>    private final String book;<br>    private RealBookParser parser; <br>    public LazyBookParser(String book) {<br>        this.book = book;<br>    }<br>    @Override<br>    public int getNumberOfPages() {<br>        if (parser == null) {<br>            parser = new RealBookParser(book);<br>        }<br>        return parser.getNumberOfPages();<br>    }<br>}</pre><p>Now:</p><pre>BookParser parser = new LazyBookParser(book);</pre><p>does <strong>not</strong> create RealBookParser.</p><p>Only when we call:</p><pre>parser.getNumberOfPages();</pre><p>does the Proxy create it.</p><p>And because the created object is stored in parser, subsequent calls reuse the same instance (already created object).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/477/0*SiROpFAactBe9moQ" /></figure><h3>2. Remote Proxy</h3><p>What if the real object exists <strong>on another server</strong>?</p><p>For example, your application needs to use a payment service running on a remote server.</p><p>Instead of making HTTP/network calls directly from your application, you can use a Proxy:</p><pre>Your Application<br>      ↓<br>Payment Proxy<br>      ↓<br> HTTP / Network<br>      ↓<br>Remote Payment Service</pre><p>Your application simply interacts with the Proxy:</p><pre>paymentService.pay(1000);</pre><p>The Proxy handles the communication with the remote service behind the scenes.</p><p>So the client doesn’t need to know about URLs, HTTP requests, or other networking details.</p><blockquote><strong><em>A Remote Proxy acts as a local representative for an object or service that exists on another system.</em></strong></blockquote><p>This is called a <strong>Remote Proxy</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/427/0*zWaOj7yo8gJd9bWr" /></figure><h3>3. Protection Proxy</h3><p>Sometimes we don’t want every user to have direct access to an object.</p><p>For example, imagine an application where only <strong>admins can delete users</strong>.</p><p>Instead of letting the client access the real service directly:</p><pre>User<br> ↓<br>Protection Proxy<br> ↓<br>&quot;Does this user have permission?&quot;<br> ↓<br>Yes → Real Service<br>No  → Access Denied</pre><p>The Proxy checks the user’s permissions before forwarding the request to the real object.</p><pre>userService.deleteUser(10);</pre><p>The client can use the same interface, while the Proxy handles the permission check behind the scenes.</p><blockquote><strong><em>A Protection Proxy controls access to an object based on permissions.</em></strong></blockquote><p>This is called a <strong>Protection Proxy</strong>.</p><h3>Dynamic Proxy — Where You See It in Real Applications</h3><p>You don’t always have to write a Proxy class yourself.</p><p>Java provides <strong>dynamic proxies</strong> through java.lang.reflect.Proxy, and frameworks such as Spring heavily use proxies.</p><p>For example, Spring can wrap a bean (means object in spring framework) in a Proxy to implement things like:</p><pre>@Transactional<br>@Cacheable</pre><p>Instead of you manually writing:</p><pre>Client → YourProxy → RealService</pre><p>Spring creates the Proxy for you at runtime.</p><p><strong>The same core idea is still there:</strong></p><pre>Client → Spring Proxy → Real Bean</pre><h3>Proxy vs Decorator</h3><p>Proxy and Decorator can look similar because both can wrap another object.</p><p>But their <strong>intent is different</strong>.</p><h3>Decorator</h3><blockquote><strong><em>“I want to add responsibilities/behavior to this object.”</em></strong></blockquote><pre>Object<br>  ↓<br>Decorator<br>  ↓<br>Additional behavior</pre><p>Decorators are commonly designed to be stacked.</p><h3>Proxy</h3><blockquote><strong><em>“I want to control access to this object.”</em></strong></blockquote><pre>Client<br>  ↓<br>Proxy<br>  ↓<br>Real Object</pre><p>The Proxy may control access through lazy creation, permission checks, remote communication, or other mechanisms.</p><h3>Proxy vs Adapter</h3><p>They may both sit between a client and another object, but their purpose is different.</p><h3>Adapter</h3><blockquote><strong><em>Changes one interface into another interface the client expects.</em></strong></blockquote><pre>Client → Adapter → Existing Object<br>          ↓<br>    Changes interface</pre><h3>Proxy</h3><blockquote><strong><em>Keeps the same interface and controls access to the real object.</em></strong></blockquote><pre>Client → Proxy → Real Object<br>          ↓<br>      Controls access</pre><h3>Proxy Pattern in One Picture</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/338/0*-1nkbJJQnwM9LIBA" /></figure><h3>Remember It Like This</h3><p>Don’t memorize the definition.</p><p>Ask:</p><blockquote><strong><em>“Do I need something in front of an object to control how it is accessed?”</em></strong></blockquote><p>If yes, <strong>Proxy</strong> is a strong candidate.</p><p><strong>Client → Proxy → Real Object</strong></p><p>The Proxy may provide <strong>lazy creation, permission checks, remote communication, or other access-control logic</strong>.</p><blockquote><strong><em>Proxy is mainly about controlling access; what it does to control that access depends on the problem.</em></strong></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ab6ccccfd66c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Observer Design Pattern — Stop Asking, “Did It Change?”]]></title>
            <link>https://medium.com/@AdvanceQuest_/observer-design-pattern-stop-asking-did-it-change-76990b86752d?source=rss-f1ae2fdec112------2</link>
            <guid isPermaLink="false">https://medium.com/p/76990b86752d</guid>
            <dc:creator><![CDATA[Hruday⚡️]]></dc:creator>
            <pubDate>Wed, 02 Sep 2026 17:32:50 GMT</pubDate>
            <atom:updated>2026-09-06T09:33:02.376Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p-TLNM4RRfCJjJ69bCA4dQ.png" /></figure><p>Imagine a weather station.</p><p>It measures:</p><ul><li>Temperature</li><li>Humidity</li><li>Pressure</li></ul><p>Now multiple displays need this information:</p><ul><li>Phone display</li><li>TV display</li><li>Forecast display</li></ul><p>Whenever the weather changes, all of them need to know.</p><p>So the question becomes:</p><blockquote><strong><em>How can we notify everyone automatically when something changes?</em></strong></blockquote><p>That’s where the <strong>Observer Design Pattern</strong> comes in.</p><h3>The Problem</h3><p>A simple approach is <strong>polling</strong>.</p><p>The phone keeps asking:</p><blockquote><em>“Did the weather change?”</em></blockquote><p>Again:</p><blockquote><em>“Did it change now?”</em></blockquote><p>And again:</p><blockquote><em>“What about now?”</em></blockquote><p>This is inefficient because most of the time, nothing has changed.</p><p>Instead of constantly asking:</p><blockquote><strong><em>“Did something change?”</em></strong></blockquote><p>We can say:</p><blockquote><strong><em>“Tell me when something changes.”</em></strong></blockquote><p>That’s the core idea behind Observer.</p><h3>The Core Idea</h3><p>The Subject maintains a list of interested Observers and notifies them whenever its state changes.</p><p>When its state changes, it automatically notifies them.</p><p>Think of it like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/547/0*9nW7H1KauxKyFoqN" /></figure><p>The Weather Station doesn’t need to know exactly what each display does.</p><p>It simply says:</p><blockquote><strong><em>“Hey, something changed. Everyone who’s interested, update yourself.”</em></strong></blockquote><p>The Observer Pattern is defined around exactly this idea: a subject maintains a list of observers and automatically notifies them when its state changes. Observers can also be added or removed at runtime.</p><h3>Observable and Observer</h3><p>There are two main sides.</p><h3>Observable / Subject</h3><p>The object whose state changes.</p><pre>WeatherStation</pre><p>It:</p><ul><li>Maintains observers</li><li>Adds observers</li><li>Removes observers</li><li>Notifies observers</li></ul><h3>Observer</h3><p>The objects interested in those changes.</p><pre>CurrentConditionsDisplay<br>ForecastDisplay</pre><p>They implement:</p><pre>update() //method for updating the new state changes</pre><p>The source follows this same structure: the Observable manages observers, while the Observer defines update().</p><h3>Let’s Build It</h3><h3>1. Observer Interface</h3><p>First, define what every observer must do.</p><pre>public interface WeatherObserver {<br>    void update();<br>}</pre><p>That’s it.</p><p>Every observer promises:</p><blockquote><em>“When the Weather Station tells me something changed, I know how to update myself.”</em></blockquote><h3>2. Observable Interface</h3><p>Now define what the Subject should support.</p><pre>public interface WeatherObservable {<br>    void addObserver(WeatherObserver observer);<br>    void removeObserver(WeatherObserver observer);<br>    void notifyObservers();<br>}</pre><p>The important operations are:</p><pre>addObserver()<br>removeObserver()<br>notifyObservers()</pre><p>These are the core mechanics of the pattern.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/410/0*syLDmZBsAZZCYt8Y" /></figure><h3>3. WeatherStation — Concrete Observable</h3><p>Now let’s implement the actual Weather Station.</p><pre>import java.util.ArrayList;<br>import java.util.List;<br><br>public class WeatherStation implements WeatherObservable {<br>    private final List&lt;WeatherObserver&gt; observers = new ArrayList&lt;&gt;();<br>    private float temperature;<br>    private float humidity;<br>    private float pressure;<br><br>    @Override<br>    public void addObserver(WeatherObserver observer) {<br>        observers.add(observer);<br>    }<br><br>    @Override<br>    public void removeObserver(WeatherObserver observer) {<br>        observers.remove(observer);<br>    }<br><br>    @Override<br>    public void notifyObservers() {<br>        for (WeatherObserver observer : observers) {<br>            observer.update();<br>        }<br>    }<br><br>    public void setWeatherReadings(float temperature, <br>                      float humidity, float pressure) {<br>        this.temperature = temperature;<br>        this.humidity = humidity;<br>        this.pressure = pressure;<br>        notifyObservers();<br>    }<br>    public float getTemperature() {<br>        return temperature;<br>    }<br>    public float getHumidity() {<br>        return humidity;<br>    }<br>    public float getPressure() {<br>        return pressure;<br>    }<br>}</pre><p>Now look carefully at this:</p><pre>for (WeatherObserver observer : observers) {<br>    observer.update();<br>}</pre><p><strong>This is the heart of the Observer Pattern.</strong></p><p>The Weather Station:</p><ol><li>Maintains a collection of observers.</li><li>Iterates over them.</li><li>Calls update() on each observer.</li></ol><p>That’s how the notification happens.</p><h3>4. CurrentConditionsDisplay</h3><p>Now let’s create our first Observer.</p><pre>public class CurrentConditionsDisplay implements WeatherObserver {<br>    private final WeatherStation weatherStation;<br><br>    public CurrentConditionsDisplay(WeatherStation weatherStation) {<br>        this.weatherStation = weatherStation;<br>    }<br><br>    @Override<br>    public void update() {<br>        float temperature = weatherStation.getTemperature();<br>        float humidity = weatherStation.getHumidity();<br>        display(temperature, humidity);<br>    }<br>    private void display(float temperature, float humidity) {<br>        System.out.println(<br>                &quot;Current Conditions: &quot;<br>                + temperature + &quot;°C, &quot;<br>                + humidity + &quot;% humidity&quot;<br>        );<br>    }<br>}</pre><p>Notice something important.</p><p>The Observer has a reference to the Weather Station.</p><p>When update() is called, it asks:</p><blockquote><em>“Okay, something changed. Give me the latest data.”</em></blockquote><p>This is called the <strong>Pull Model</strong>.</p><h3>5. ForecastDisplay</h3><p>We can have another Observer with completely different behavior.</p><pre>public class ForecastDisplay implements WeatherObserver {<br>    private final WeatherStation weatherStation;<br>    public ForecastDisplay(<br>            WeatherStation weatherStation) {<br>        this.weatherStation = weatherStation;<br>    }<br>    @Override<br>    public void update() {<br>        float pressure = weatherStation.getPressure();<br>        if (pressure &lt; 30) {<br>            System.out.println(&quot;Forecast: Rainy weather&quot;);<br>        } else {<br>            System.out.println(&quot;Forecast: Weather looks good&quot;);<br>        }<br>    }<br>}</pre><p>Notice:</p><p>Both classes implement:</p><pre>WeatherObserver</pre><p>But they react differently.</p><pre>CurrentConditionsDisplay<br>        ↓<br>Shows current temperature/humidity<br><br><br>ForecastDisplay<br>        ↓<br>Predicts weather using pressure</pre><p>That’s an important Observer characteristic: <strong>many observers can react differently to the same event.</strong></p><h3>6. Register the Observers</h3><p>Now let’s connect everything.</p><pre>public class WeatherStationApp {<br>    public static void main(String[] args) {<br>        WeatherStation weatherStation = new WeatherStation();<br><br>        CurrentConditionsDisplay currentDisplay = <br>                new CurrentConditionsDisplay(weatherStation);<br><br>        ForecastDisplay forecastDisplay =<br>                new ForecastDisplay(weatherStation);<br>        weatherStation.addObserver(currentDisplay);<br>        weatherStation.addObserver(forecastDisplay);<br>        weatherStation.setWeatherReadings(32, 70, 30.4f);<br>    }<br>}</pre><p>When this runs:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/691/0*ikMyNRUhk2m1iavq" /></figure><p>So one state change can trigger multiple observers.</p><h3>What If We Remove an Observer?</h3><p>This is another important part of Observer.</p><p>Suppose the Forecast Display is no longer interested.</p><pre>weatherStation.removeObserver(forecastDisplay);</pre><p>Now:</p><pre>weatherStation.setWeatherReadings(35,60,29.2f);</pre><p>Only the remaining observers are notified.</p><p>The source demonstrates exactly this behavior: after removing the forecast display, it no longer receives the third weather update.</p><h3>Pull vs Push</h3><p>This is a <strong>good interview question</strong>.</p><h3>Pull Model</h3><p>The Subject only says:</p><blockquote><em>“Something changed.”</em></blockquote><pre>observer.update();</pre><p>Then the Observer asks for the latest state:</p><pre>weatherStation.getTemperature();<br>weatherStation.getHumidity();<br>weatherStation.getPressure();</pre><p>That’s what our example uses.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/380/0*loMsHuB9HKv7rHzY" /></figure><h3>Push Model</h3><p>Instead of making the Observer ask for the data, the Subject sends the data directly.</p><p>For example:</p><pre>void update(float temperature, float humidity, float pressure);</pre><p>Then:</p><pre>observer.update(temperature,humidity,pressure);</pre><p>So:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/258/0*X7_n6ghBNwg_0HxQ" /></figure><p><strong>Interview takeaway:</strong> Observer can be implemented using either <strong>pull</strong> or <strong>push</strong>.</p><ul><li>Use <strong>Push</strong> when all your observers always need the exact same, lightweight data.</li><li>Use <strong>Pull</strong> when you have many different types of observers that need different subsets of complex data.</li></ul><h3>Why Is This Better?</h3><p>Without Observer, the Weather Station could directly depend on every display:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/738/0*1p_q9zoL1PL6rV98" /></figure><p>Then every time we add a new display, we need to modify the Weather Station.</p><p>With Observer:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/738/0*vd2aIZr2xTy5_yGo" /></figure><p>The Weather Station only knows:</p><blockquote><strong><em>“I have WeatherObservers.”</em></strong></blockquote><p>It doesn’t care about their concrete implementations.</p><p>This gives us <strong>looser coupling</strong> and makes it easier to add or remove observers.</p><h3>Real-World Example — “Notify Me When Available”</h3><p>Imagine an e-commerce product.</p><p>The product is currently:</p><pre>Out of Stock</pre><p>You click:</p><blockquote><strong><em>Notify Me When Available</em></strong></blockquote><p>You become an Observer.</p><p>The product/inventory system becomes the Observable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/289/0*BPz9x0xGBp3vjUaX" /></figure><p>When the product becomes available:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/327/0*w6WtcYhP7LJVKUNZ" /></figure><p>The same Observer idea appears in weather apps, social feeds, subscriptions, stock trackers, and product notifications.</p><h3>The 3 Important Parts</h3><p>For interviews, remember these:</p><h3>1. Subject / Observable</h3><p>Maintains observers and notifies them.</p><pre>WeatherStation</pre><h3>2. Observer</h3><p>Defines the notification behavior.</p><pre>WeatherObserver<br>    ↓<br>  update()</pre><h3>3. Concrete Observers</h3><p>Different objects that react to the same change.</p><pre>CurrentConditionsDisplay<br>ForecastDisplay<br>TVDisplay<br>MobileDisplay</pre><p>The source explicitly separates these roles into Observable, Observer, Concrete Observable, and Concrete Observers.</p><h3>Observer Pattern in One Sentence</h3><blockquote><strong><em>Let objects subscribe to another object so that when its state changes, all subscribers are automatically notified.</em></strong></blockquote><h3>Observer vs Publisher-Subscriber (pub/sub)</h3><blockquote><em>In Observer, the Subject usually knows its Observers directly and notifies them. In Pub/Sub, publishers and subscribers are typically decoupled through a message broker/event bus.</em></blockquote><h3>Final Mental Model</h3><p>Remember this flow:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/342/0*3QVOZae-lpAzZXsT" /></figure><p>Or simply:</p><blockquote><strong><em>Don’t keep asking, “Did something change?”<br>Subscribe once, and let the object tell you when it changes.</em></strong></blockquote><h3>Interview Cheat Sheet</h3><p>If the interviewer asks <strong>“Explain Observer Pattern”</strong>, you should be able to say:</p><blockquote><em>“Observer is a behavioral design pattern where a Subject maintains a list of Observers. When the Subject’s state changes, it notifies all registered Observers. Observers can subscribe and unsubscribe at runtime. The notification can follow either a pull model, where observers fetch the latest state, or a push model, where the subject sends the changed data.”</em></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=76990b86752d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Strategy Design Pattern — Stop Fighting Inheritance]]></title>
            <link>https://medium.com/@AdvanceQuest_/strategy-design-pattern-stop-fighting-inheritance-a14fcdc1d8cb?source=rss-f1ae2fdec112------2</link>
            <guid isPermaLink="false">https://medium.com/p/a14fcdc1d8cb</guid>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[design-systems]]></category>
            <category><![CDATA[lld]]></category>
            <category><![CDATA[low-level-design]]></category>
            <category><![CDATA[strategy-pattern]]></category>
            <dc:creator><![CDATA[Hruday⚡️]]></dc:creator>
            <pubDate>Tue, 01 Sep 2026 19:13:02 GMT</pubDate>
            <atom:updated>2026-09-01T19:13:02.721Z</atom:updated>
            <content:encoded><![CDATA[<p>When I first started learning Design Patterns, the <strong>Strategy Design Pattern</strong> felt like one of those definitions that sounds simple but doesn’t really explain anything:</p><blockquote><strong><em>“Define a family of algorithms, encapsulate each one, and make them interchangeable.”</em></strong></blockquote><p>Okay… but what does that actually mean?</p><p>Let’s understand it intuitively with a simple example.</p><h3>First, What Problem Are Design Patterns Solving?</h3><p>Software is never really finished.</p><p>Requirements change.<br>Features change.<br>Business rules change.</p><p>And if every new requirement forces us to modify a lot of existing code, our design becomes difficult to maintain.</p><p>A good design tries to make these changes <strong>as isolated as possible</strong>.</p><p>One useful way to think about Design Patterns is:</p><blockquote><strong><em>Identify what changes frequently and separate it from what doesn’t change.</em></strong></blockquote><p>That’s exactly the idea we’ll use for the Strategy Pattern.</p><h3>Let’s Start With a Robot</h3><p>Imagine we’re building a robot simulation.</p><p>We have different types of robots:</p><ul><li>Companion Robot</li><li>Worker Robot</li><li>Sparrow Robot</li><li>Jet Robot</li><li>etc.</li></ul><p>Robots can have different behaviors, such as:</p><pre>walk();<br>talk();<br>fly();</pre><p>And every robot may look different:</p><pre>display();</pre><p>So we might initially create something like:</p><pre>abstract class Robot {<br>    void walk() {<br>        System.out.println(&quot;Walking&quot;);<br>    }<br>    void talk() {<br>        System.out.println(&quot;Talking&quot;);<br>    }<br>    abstract void display();<br>}</pre><p>Then we create different robots:</p><pre>class CompanionRobot extends Robot {<br>    @Override<br>    void display() {<br>        System.out.println(&quot;Displaying Companion Robot&quot;);<br>    }<br>}</pre><pre>class WorkerRobot extends Robot {<br>    @Override<br>    void display() {<br>        System.out.println(&quot;Displaying Worker Robot&quot;);<br>    }<br>}</pre><p>So far, everything looks fine.</p><p>But then…</p><h3>The Problem Begins</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/870/0*JIRHKzLzxaSFHW8y" /></figure><p>Tomorrow, we introduce a robot that can <strong>fly</strong>.</p><p>Let’s call it:</p><pre>class SparrowRobot extends Robot</pre><p>We need to add:</p><pre>void fly() {<br>    System.out.println(&quot;Flying&quot;);<br>}</pre><p>No big deal.</p><p>But now another flying robot comes.</p><p>And another.<br>And another.<br>If every flying robot needs the same fly() implementation, we may start copying the same code into multiple classes.</p><p>That’s already a smell.</p><p>We are violating:</p><blockquote><strong><em>DRY — Don’t Repeat Yourself.</em></strong></blockquote><p>So we might think:</p><h3>“Why not move fly() into the parent class?&quot;</h3><p>Something like:</p><pre>abstract class Robot {<br>    void walk() {<br>        System.out.println(&quot;Walking&quot;);<br>    }<br>    void talk() {<br>        System.out.println(&quot;Talking&quot;);<br>    }<br>    void fly() {<br>        System.out.println(&quot;Flying&quot;);<br>    }<br>    abstract void display();<br>}</pre><p>Sounds better.</p><p>But now we have another problem.<br>What if a CompanionRobot <strong>cannot fly</strong>?<br>It inherited fly() anyway.</p><p>We could override it:</p><pre>void fly() {<br>    System.out.println(&quot;Cannot fly&quot;);<br>}</pre><p>But that’s ugly. <br>We’re inheriting behavior that the robot shouldn’t have in the first place.</p><h3>“Let’s Use More Inheritance!”</h3><p>We might try to fix this with a more complicated hierarchy:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*F7vcZ5FL1v6q69eD" /></figure><p>Now imagine there are different ways of flying:</p><ul><li>Flying with wings</li><li>Flying with a jet engine</li></ul><p>And different ways of walking:</p><ul><li>Normal walking</li><li>Cannot walk</li></ul><p>And different ways of talking:</p><ul><li>Normal talking</li><li>Cannot talk</li></ul><p>Our inheritance tree starts exploding.</p><p>We end up creating classes for different combinations of behaviors.</p><p>And the combinations keep increasing.</p><p>This is the real problem.</p><blockquote><strong><em>The more behaviors we add, the more complicated our inheritance hierarchy becomes.</em></strong></blockquote><p>And that’s a dangerous path.</p><p>A useful principle here is:</p><blockquote><strong><em>The solution to inheritance is not more inheritance.</em></strong></blockquote><p>So what can we do instead?</p><h3>The Key Idea: Separate What Changes</h3><p>Let’s look at our Robot.</p><p>What is relatively stable?<br>The robot’s identity and appearance.</p><pre>display();</pre><p>Each robot has its own appearance.</p><p>But what keeps changing?</p><pre>walk();<br>talk();<br>fly();</pre><p>There can be many different implementations of these behaviors.</p><p>So why are we keeping these changing behaviors inside Robot?</p><h3>Let’s take them out.</h3><p>Instead of making Robot responsible for knowing how to walk, talk, and fly, we move those changing behaviors into separate strategy objects.</p><p>This is where the <strong>Strategy Pattern</strong> comes in.</p><h3>Strategy Pattern</h3><p>The basic idea is:</p><blockquote><strong><em>Take behaviors that can vary and encapsulate them into separate classes.</em></strong></blockquote><p>For example, instead of putting walking logic directly inside Robot, create a strategy for walking.</p><pre>interface Walkable {<br>  void walk();<br>}</pre><p>Then we can have different walking strategies.</p><pre>class NormalWalk implements Walkable {<br>    @Override<br>    public void walk() {<br>        System.out.println(&quot;Walking normally&quot;);<br>    }<br>}</pre><p>And:</p><pre>class NoWalk implements Walkable {<br>    @Override<br>    public void walk() {<br>        System.out.println(&quot;Cannot walk&quot;);<br>    }<br>}</pre><p>Now walking behavior is separated from the robot.</p><h3>Do the Same for Talking</h3><pre>interface Talkable {<br>    void talk();<br>}</pre><p>Normal talking:</p><pre>class NormalTalk implements Talkable {<br>    @Override<br>    public void talk() {<br>        System.out.println(&quot;Talking normally&quot;);<br>    }<br>}</pre><p>No talking:</p><pre>class NoTalk implements Talkable {<br>    @Override<br>    public void talk() {<br>        System.out.println(&quot;Cannot talk&quot;);<br>    }<br>}</pre><h3>And Flying</h3><pre>interface Flyable {<br>    void fly();<br>}</pre><p>Normal flying:</p><pre>class NormalFly implements Flyable {<br>    @Override<br>    public void fly() {<br>        System.out.println(&quot;Flying normally&quot;);<br>    }<br>}</pre><p>No flying:</p><pre>class NoFly implements Flyable {<br>    @Override<br>    public void fly() {<br>        System.out.println(&quot;Cannot fly&quot;);<br>    }<br>}</pre><p>We could even create:</p><pre>class JetFly implements Flyable {<br>    @Override<br>    public void fly() {<br>        System.out.println(&quot;Flying using a jet engine&quot;);<br>    }<br>}</pre><p>Now we have completely separated the behaviors.</p><h3>But How Does Robot Use Them?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/912/0*zkFZEOvUsSckdWDI" /></figure><p>Here’s the important part.</p><p>Instead of <strong>inheriting</strong> these behaviors, our Robot will <strong>contain</strong> them.</p><p>This is called <strong>composition</strong>.</p><pre>abstract class Robot {<br>    private final Walkable walkable;<br>    private final Talkable talkable;<br>    private final Flyable flyable;<br>    Robot(<br>        Walkable walkable,<br>        Talkable talkable,<br>        Flyable flyable<br>    ) {<br>        this.walkable = walkable;<br>        this.talkable = talkable;<br>        this.flyable = flyable;<br>    }<br>    void walk() {<br>        walkable.walk();<br>    }<br>    void talk() {<br>        talkable.talk();<br>    }<br>    void fly() {<br>        flyable.fly();<br>    }<br>    <br>    abstract void display();<br>}</pre><p>Notice something important.</p><p>Robot doesn&#39;t actually know <strong>how</strong> to walk.</p><p>It simply says:</p><pre>walkable.walk();</pre><p>It delegates the responsibility to the walking strategy.</p><p>The same thing happens for:</p><pre>talkable.talk();<br>flyable.fly();</pre><h3>Now Look How Powerful This Becomes</h3><p>Let’s create a companion robot.</p><pre>class CompanionRobot extends Robot {<br>    CompanionRobot() {<br>        super(<br>            new NormalWalk(),<br>            new NormalTalk(),<br>            new NoFly()<br>        );<br>    }<br>    @Override<br>    void display() {<br>        System.out.println(&quot;Displaying Companion Robot&quot;);<br>    }<br>}</pre><p>Our companion robot now has:</p><ul><li>Normal walking</li><li>Normal talking</li><li>No flying</li></ul><p>And we didn’t need to create a complicated inheritance hierarchy.</p><p>Now imagine a different robot:</p><pre>class JetRobot extends Robot {<br>    JetRobot() {<br>        super(<br>            new NormalWalk(),<br>            new NoTalk(),<br>            new JetFly()<br>        );<br>    }<br>    @Override<br>    void display() {<br>        System.out.println(&quot;Displaying Jet Robot&quot;);<br>    }<br>}</pre><p>This robot has:</p><ul><li>Normal walking</li><li>No talking</li><li>Jet flying</li></ul><p>And notice what happened.<br>We simply <strong>combined different behaviors</strong>.</p><h3>This Is the Magic of Strategy</h3><p>Suppose tomorrow we create:</p><pre>class FastWalk implements Walkable {<br>    @Override<br>    public void walk() {<br>        System.out.println(&quot;Walking very fast&quot;);<br>    }<br>}</pre><p>We don’t need to modify Robot.</p><p>We don’t need to modify CompanionRobot.</p><p>We simply create a new strategy.</p><p>And we can use it wherever we need:</p><pre>new FastWalk()</pre><p>Because Robot depends on the Walkable interface, we can replace one walking strategy with another without changing the Robot itself.</p><p>That’s what makes the strategies <strong>interchangeable</strong>.</p><h3>Composition Instead of Inheritance</h3><p>This is one of the biggest lessons from the Strategy Pattern.</p><p>Instead of saying:</p><blockquote><em>“A robot </em><strong><em>is a</em></strong><em> NormalWalker.”</em></blockquote><p>we say:</p><blockquote><em>“A robot </em><strong><em>has a</em></strong><em> walking strategy.”</em></blockquote><p>That’s composition.</p><h3>Inheritance</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/416/0*t0orbLLTS_Ox6dmF" /></figure><h3>Composition</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/870/0*l0f84hnZBUyNsp6Y" /></figure><p>Now each behavior can evolve independently.</p><h3>What Does “Strategy” Actually Mean?</h3><p>The word <strong>strategy</strong> is easier to understand if you think of it as:</p><blockquote><strong><em>A particular way of doing something.</em></strong></blockquote><p>For example, suppose you want to travel from Hyderabad to Bangalore.</p><p>You could choose:</p><ul><li>Flight</li><li>Train</li><li>Bus</li><li>Car</li></ul><p>Your destination hasn’t changed.</p><p>Only your <strong>strategy for reaching the destination</strong> changes.</p><p>That’s the same idea in software.</p><p>The main object has a goal, but there are multiple ways of performing a particular operation.</p><p>So we encapsulate those different approaches as strategies.</p><h3>The Three Important Parts</h3><p>The Strategy Pattern has three important pieces.</p><h3>1. Strategy</h3><p>The interface that defines the common behavior.</p><pre>interface Flyable {<br>    void fly();<br>}</pre><h3>2. Concrete Strategies</h3><p>The different implementations.</p><pre>class NormalFly implements Flyable {<br>    public void fly() {<br>        System.out.println(&quot;Flying normally&quot;);<br>    }<br>}</pre><pre>class JetFly implements Flyable {<br>    public void fly() {<br>        System.out.println(&quot;Flying using a jet&quot;);<br>    }<br>}</pre><h3>3. Context</h3><p>The object that <strong>uses</strong> the strategy.</p><p>In our example:</p><pre>class Robot</pre><p>The robot holds a strategy and delegates the work to it.</p><pre>void fly() {<br>    flyable.fly();<br>}</pre><p>So conceptually:</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/0*UmpPWtOpe7t2tMhk" /></figure><h3>A Real-World Example: Payment</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/615/0*Do2fy5fk5UUStGUF" /></figure><p>Let’s forget robots for a moment.</p><p>Imagine we have:</p><pre>class PaymentService {<br>    void pay() {<br>        // payment logic<br>    }<br>}</pre><p>But there are multiple ways to pay:</p><ul><li>UPI</li><li>Credit Card</li><li>Debit Card</li><li>Net Banking</li></ul><p>If we put all of these inside PaymentService, we&#39;ll eventually get a huge collection of if-else statements.</p><p>Instead:</p><pre>interface PaymentStrategy {<br>    void pay();<br>}</pre><p>Then:</p><pre>class UpiPayment implements PaymentStrategy {<br>    public void pay() {<br>        System.out.println(&quot;Paying using UPI&quot;);<br>    }<br>}</pre><pre>class CreditCardPayment implements PaymentStrategy {<br>    public void pay() {<br>        System.out.println(&quot;Paying using Credit Card&quot;);<br>    }<br>}</pre><p>And our payment service simply uses the selected strategy:</p><pre>class PaymentService {<br>    private final PaymentStrategy strategy;<br>    PaymentService(PaymentStrategy strategy) {<br>        this.strategy = strategy;<br>    }<br>    void pay() {<br>        strategy.pay();<br>    }<br>}</pre><p>Now:</p><pre>PaymentService payment = new PaymentService(new UpiPayment());<br>payment.pay();</pre><p>Or:</p><pre>PaymentService payment = new PaymentService(new CreditCardPayment());<br>payment.pay();</pre><p>The payment service only depends on the PaymentStrategy interface, so new payment methods can be added without changing the service.</p><p>Another Classic Example: <strong>Sorting</strong></p><p>Suppose we have:</p><pre>class Sorter {<br>  void sort() {<br>        // sorting logic<br>    }<br>}</pre><p>But we can sort using:</p><ul><li>Quick Sort</li><li>Merge Sort</li><li>Insertion Sort</li></ul><p>Each algorithm can become a strategy.</p><pre>interface SortingStrategy {<br>    void sort(int[] array);<br>}</pre><p>Then:</p><pre>class QuickSort implements SortingStrategy {<br>    public void sort(int[] array) {<br>        System.out.println(&quot;Quick Sort&quot;);<br>    }<br>}</pre><pre>class MergeSort implements SortingStrategy {<br>    public void sort(int[] array) {<br>        System.out.println(&quot;Merge Sort&quot;);<br>    }<br>}</pre><p>The sorter doesn’t care which algorithm is being used.</p><pre>class Sorter {<br>    private final SortingStrategy strategy;<br>    Sorter(SortingStrategy strategy) {<br>        this.strategy = strategy;<br>    }<br>    void sort(int[] array) {<br>        strategy.sort(array);<br>    }<br>}</pre><p>That’s another Strategy Pattern.</p><h3>The Most Important Benefit</h3><p>The biggest benefit isn’t simply “we used interfaces.”</p><p>The real benefit is:</p><blockquote><strong><em>We separated code that changes from code that doesn’t.</em></strong></blockquote><p>If tomorrow we add:</p><pre>class HeapSort implements SortingStrategy</pre><p>the existing Sorter doesn&#39;t need to change.</p><p>If tomorrow we add:</p><pre>class ApplePay implements PaymentStrategy</pre><p>the existing PaymentService doesn&#39;t need to change.</p><p>We’re extending the system instead of constantly modifying the existing core logic.</p><p>This aligns nicely with the <strong>Open/Closed Principle</strong>:</p><blockquote><strong><em>Software entities should be open for extension but closed for modification.</em></strong></blockquote><h3>When Should You Think About Strategy Pattern?</h3><p>Whenever you see something like:</p><pre>if (type == A) {<br>    // algorithm A<br>}<br>else if (type == B) {<br>    // algorithm B<br>}<br>else if (type == C) {<br>    // algorithm C<br>}</pre><p>Ask yourself:</p><blockquote><strong><em>Are these different ways of performing the same operation?</em></strong></blockquote><p>If yes, Strategy Pattern might be a good candidate.</p><p>For example:</p><pre>Different payment methods<br>Different sorting algorithms<br>Different pricing algorithms<br>Different discount calculations<br>Different notification mechanisms<br>Different routing algorithms<br>Different authentication mechanisms</pre><p>The key isn’t the if-else itself.</p><p>The key is that <strong>the behavior varies independently</strong>.</p><h3>One Important Clarification</h3><p>Strategy Pattern does <strong>not</strong> mean:</p><blockquote><em>“Never use inheritance.”</em></blockquote><p>Inheritance is not inherently bad.</p><p>It can be very useful when there is a genuine <strong>is-a</strong> relationship and the hierarchy is stable.</p><p>The problem occurs when we’re using inheritance primarily to share behaviors that vary independently.</p><p>In those situations, composition can be much more flexible.</p><p>That’s why a useful rule of thumb is:</p><blockquote><strong><em>Favor composition over inheritance.</em></strong></blockquote><h3>Strategy Pattern in One Sentence</h3><p>If I had to explain the entire pattern in one sentence:</p><blockquote><strong><em>Strategy Pattern takes interchangeable behaviors, puts each behavior into its own class, and lets the main object use whichever behavior it needs through composition.</em></strong></blockquote><p>Or even more simply:</p><blockquote><strong><em>Don’t hard-code a behavior inside a class when that behavior is likely to change — extract it into a strategy.</em></strong></blockquote><h3>Final Mental Model</h3><p>Whenever you’re designing a system, ask:</p><h3>1. What part of my code changes frequently?</h3><p>For example:</p><pre>Walking<br>Talking<br>Flying<br>Payment<br>Sorting<br>Pricing</pre><h3>2. Can I separate those behaviors?</h3><p>Create an interface:</p><pre>interface Strategy {<br>    void execute();<br>}</pre><h3>3. Can I create multiple implementations?</h3><pre>class StrategyA implements Strategy<br>class StrategyB implements Strategy<br>class StrategyC implements Strategy</pre><h3>4. Can the main class simply delegate to the strategy?</h3><pre>strategy.execute();</pre><p>If yes, you are probably looking at a Strategy Pattern.</p><p>The Context doesn’t need to know the implementation details.</p><p>It simply says:</p><blockquote><strong><em>“I need this operation. Strategy, you handle it.”</em></strong></blockquote><p>And that’s the heart of the Strategy Design Pattern.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a14fcdc1d8cb" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>