<?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 Harshal Gupta on Medium]]></title>
        <description><![CDATA[Stories by Harshal Gupta on Medium]]></description>
        <link>https://medium.com/@gupta_harshal?source=rss-43619e04b875------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*UX3tbiOGLkXAnrWybN9JqA.png</url>
            <title>Stories by Harshal Gupta on Medium</title>
            <link>https://medium.com/@gupta_harshal?source=rss-43619e04b875------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 00:29:29 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@gupta_harshal/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[Understanding the Bridge Design Pattern]]></title>
            <link>https://medium.com/@gupta_harshal/understanding-the-bridge-design-pattern-c5c285df0bcd?source=rss-43619e04b875------2</link>
            <guid isPermaLink="false">https://medium.com/p/c5c285df0bcd</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[low-level-design]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Harshal Gupta]]></dc:creator>
            <pubDate>Mon, 17 Aug 2026 02:24:25 GMT</pubDate>
            <atom:updated>2026-08-17T03:48:37.901Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>The <strong>Bridge Design Pattern</strong> decouples an <strong>Abstraction</strong> (the high-level control logic) from its <strong>Implementation</strong> (the underlying hardware platform) so that both hierarchies can vary independently without causing a massive explosion of classes.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/971/1*kyAWXts_pV_VMESm0ZgODw.png" /></figure><p>Imagine you buy a Sony TV and a Sony Remote. Later, you buy a Philips Radio, requiring a Philips Remote. If you want a remote with a “Mute” button, you suddenly need a <em>Sony Advanced Remote</em> and a <em>Philips Advanced Remote</em>.</p><p>If you use classic inheritance, <strong>every new device forces you to create a new remote class.</strong></p><p>The <strong>Bridge Pattern</strong> fixes this by separating <strong>the controller in your hand</strong> (Abstraction) from <strong>the machine on the wall</strong> (Implementor). The remote doesn’t care <em>what</em> it is controlling; it only knows how to send standard signals across a “bridge” wire.</p><h3>Code Sample</h3><pre>// 1. IMPLEMENTOR INTERFACE (The low-level platform-dependent interface)<br>interface Device {<br>    boolean isEnabled();<br>    void enable();<br>    void disable();<br>    int getVolume();<br>    void setVolume(int percent);<br>}<br><br>// 2. CONCRETE IMPLEMENTORS (The platform-specific hardware logic)<br>class TV implements Device {<br>    private boolean on = false;<br>    private int volume = 30;<br><br>    @Override public boolean isEnabled() { return on; }<br>    @Override public void enable() { on = true; System.out.println(&quot;TV: Powered ON&quot;); }<br>    @Override public void disable() { on = false; System.out.println(&quot;TV: Powered OFF&quot;); }<br>    @Override public int getVolume() { return volume; }<br>    @Override public void setVolume(int percent) { this.volume = percent; System.out.println(&quot;TV: Volume adjusted to &quot; + percent + &quot;%&quot;); }<br>}<br><br>class Radio implements Device {<br>    private boolean on = false;<br>    private int volume = 15;<br><br>    @Override public boolean isEnabled() { return on; }<br>    @Override public void enable() { on = true; System.out.println(&quot;Radio: Powered ON&quot;); }<br>    @Override public void disable() { on = false; System.out.println(&quot;Radio: Powered OFF&quot;); }<br>    @Override public int getVolume() { return volume; }<br>    @Override public void setVolume(int percent) { this.volume = percent; System.out.println(&quot;Radio: Volume adjusted to &quot; + percent + &quot;%&quot;); }<br>}<br><br>// 3. ABSTRACTION (The high-level control logic containing the &quot;bridge&quot; reference to an Implementor)<br>class RemoteControl {<br>    protected Device device; // The Bridge reference<br><br>    public RemoteControl(Device device) {<br>        this.device = device;<br>    }<br><br>    public void togglePower() {<br>        if (device.isEnabled()) {<br>            device.disable();<br>        } else {<br>            device.enable();<br>        }<br>    }<br><br>    public void volumeUp() {<br>        device.setVolume(device.getVolume() + 10);<br>    }<br>}<br><br>// 4. REFINED ABSTRACTION (An extended control interface without changing the hardware layer)<br>class AdvancedRemoteControl extends RemoteControl {<br>    public AdvancedRemoteControl(Device device) {<br>        super(device);<br>    }<br><br>    public void mute() {<br>        System.out.println(&quot;Advanced Remote: Activating Mute Mode&quot;);<br>        device.setVolume(0);<br>    }<br>}<br><br>// 5. CLIENT CODE<br>public class Main {<br>    public static void main(String[] args) {<br>        // Instantiate the hardware components<br>        Device sonyTV = new TV();<br>        Device phillipsRadio = new Radio();<br><br>        System.out.println(&quot;=== Testing Basic Remote with a TV ===&quot;);<br>        RemoteControl basicRemote = new RemoteControl(sonyTV);<br>        basicRemote.togglePower();<br>        basicRemote.volumeUp();<br><br>        System.out.println(&quot;\n=== Testing Advanced Remote with a Radio ===&quot;);<br>        AdvancedRemoteControl advancedRemote = new AdvancedRemoteControl(phillipsRadio);<br>        advancedRemote.togglePower();<br>        advancedRemote.volumeUp();<br>        advancedRemote.mute(); // Access specialized abstraction feature<br>    }<br>}</pre><p><strong>1. The Implementor Layer (</strong><strong>Device)</strong> The Device interface serves as the low-level contract. It declares only primitive operations (enable(), setVolume()) that every piece of hardware must support. It has zero knowledge of how remotes operate.</p><p><strong>2. The Concrete Implementors (</strong><strong>TV and </strong><strong>Radio)</strong> These classes represent the actual physical platforms. Each maintains its own state (volume, on/off) and implements the primitive operations specific to its hardware logic.</p><p><strong>3. The Abstraction &amp; The “Bridge” (</strong><strong>RemoteControl)</strong> The field protected Device device; inside RemoteControl is the literal <strong>Bridge</strong>. Instead of doing heavy lifting itself, RemoteControl delegates hardware commands to the bridged device reference (device.setVolume(...)).</p><p><strong>4. The Refined Abstraction (</strong><strong>AdvancedRemoteControl)</strong> Demonstrates how the control layer can grow independently. The mute() method adds a new high-level feature by orchestrating lower-level primitive calls (device.setVolume(0)) without changing the Device interface or any hardware implementation.</p><p><strong>5. The Client Flow (</strong><strong>Main)</strong> Shows runtime flexibility in action. Any concrete remote can be paired with any concrete device during object instantiation (new AdvancedRemoteControl(phillipsRadio)), proving that the control logic and hardware layers are truly decoupled.</p><ul><li><strong>Composition Over Inheritance:</strong> Instead of forcing remotes to inherit directly from hardware devices, the code uses a “has-a” relationship (RemoteControl <em>has a</em> Device). This bridges the two hierarchies dynamically at runtime.</li><li><strong>Elimination of Class Explosion:</strong> Standard inheritance forces you to create N * M classes (e.g., TVBasicRemote, RadioAdvancedRemote). The Bridge pattern reduces this to N + M, keeping your codebase lean as new features or hardware arrive.</li><li><strong>Single Responsibility Principle (SRP):</strong> High-level user interface logic lives entirely within RemoteControl, while low-level hardware state management lives inside TV and Radio.</li><li><strong>Open/Closed Principle (OCP):</strong> You can introduce a brand-new hardware device (like a Projector) or a new remote type (like a VoiceRemote) without altering a single line of existing code.</li></ul><h3>Real World Use Cases</h3><p><strong>1. Cross-Platform GUI Frameworks (e.g., Flutter, Java AWT/Swing)</strong></p><ul><li><strong>The Abstraction:</strong> High-level UI elements like Window, Button, or TextField that developers interact with.</li><li><strong>The Implementor:</strong> Platform-specific graphics engines (Windows API, macOS Cocoa, Linux X11).</li><li><strong>How Bridge Works:</strong> You create a single Button component in code. Behind the scenes, the Button uses a bridge to delegate drawing to WindowsButtonPeer or MacButtonPeer depending on where the app is running.</li></ul><p><strong>2. Database Drivers (JDBC / ORM Frameworks)</strong></p><ul><li><strong>The Abstraction:</strong> Standard query methods used by applications (e.g., executeQuery(), connect()).</li><li><strong>The Implementor:</strong> Database-specific driver implementations (e.g., PostgreSQL, MySQL, Oracle, SQLite).</li><li><strong>How Bridge Works:</strong> Your application code calls a generic DatabaseConnection abstraction. The driver acts as the bridge that translates those high-level SQL commands into specific raw binary protocols for MySQL or Postgres under the hood.</li></ul><p><strong>3. Multi-Channel Notification Engines</strong></p><ul><li><strong>The Abstraction:</strong> Message types like AlertNotification, MarketingNotification, or TwoFactorAuthNotification.</li><li><strong>The Implementor:</strong> Delivery channels like EmailProvider, SMSGateway, or PushNotificationService.</li><li><strong>How Bridge Works:</strong> An UrgentAlert object can be bridged dynamically to send via Twilio (SMS), SendGrid (Email), or Firebase (Push) without modifying the message format logic.</li></ul><p><strong>4. Payment Gateway Integration</strong></p><ul><li><strong>The Abstraction:</strong> Checkout workflows like OneClickCheckout, SubscriptionBilling, or GuestCheckout.</li><li><strong>The Implementor:</strong> Third-party payment APIs like StripeAPI, PayPalAPI, or RazorpayAPI.</li><li><strong>How Bridge Works:</strong> You write subscription logic once inside the abstraction layer. Switching or adding payment providers simply requires plugging a new vendor implementation into the existing bridge.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c5c285df0bcd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding the Flyweight Design Pattern]]></title>
            <link>https://medium.com/@gupta_harshal/understanding-the-flyweight-design-pattern-3770dab87236?source=rss-43619e04b875------2</link>
            <guid isPermaLink="false">https://medium.com/p/3770dab87236</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[low-level-design]]></category>
            <dc:creator><![CDATA[Harshal Gupta]]></dc:creator>
            <pubDate>Sun, 16 Aug 2026 00:38:35 GMT</pubDate>
            <atom:updated>2026-08-16T00:38:35.409Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>The <strong>Flyweight Design Pattern</strong> is a structural pattern focused on aggressive memory optimization. It prevents application slowdowns and memory overflow when handling thousands or millions of fine-grained objects by sharing constant, heavy data across instances rather than duplicating it in memory.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/971/1*VJ3XFMfjTMgPJmcb9chNzw.png" /></figure><h3>Code Sample</h3><pre>import java.util.HashMap;<br>import java.util.Map;<br><br>// 1. FLYWEIGHT INTERFACE (Defines how the flyweight accepts extrinsic state)<br>interface Bullet {<br>    void render(int x, int y, int speed); // x, y, speed are extrinsic states<br>}<br><br>// 2. CONCRETE FLYWEIGHT (Stores intrinsic state: immutable, shared data)<br>class ConcreteBulletType implements Bullet {<br>    private final String color;<br>    private final String texture; // Representing a heavy 3D asset/image reference<br><br>    public ConcreteBulletType(String color, String texture) {<br>        this.color = color;<br>        this.texture = texture;<br>        // Simulate a heavy asset loading process once<br>        System.out.println(&quot;System: [Heavy Asset Loaded] Created bullet type with color &quot; + color);<br>    }<br><br>    @Override<br>    public void render(int x, int y, int speed) {<br>        System.out.println(&quot;Rendering &quot; + color + &quot; bullet at (&quot; + x + &quot;, &quot; + y + &quot;) traveling at speed &quot; + speed + &quot;mph.&quot;);<br>    }<br>}<br><br>// 3. FLYWEIGHT FACTORY (Manages caching and reuse of Flyweight objects)<br>class BulletFactory {<br>    private static final Map&lt;String, Bullet&gt; bulletCache = new HashMap&lt;&gt;();<br><br>    public static Bullet getBulletType(String color, String texture) {<br>        String key = color + &quot;_&quot; + texture;<br>        <br>        // Reuse existing flyweight instance if available<br>        if (!bulletCache.containsKey(key)) {<br>            bulletCache.put(key, new ConcreteBulletType(color, texture));<br>        }<br>        return bulletCache.get(key);<br>    }<br>}<br><br>// 4. CLIENT (Maintains unique extrinsic coordinates and triggers operations)<br>public class Main {<br>    public static void main(String[] args) {<br>        // We want to fire 5 bullets, but we will only allocate memory for 2 distinct types!<br>        <br>        System.out.println(&quot;=== Simulation Initiated ===&quot;);<br>        <br>        // Player 1 fires 3 red bullets<br>        Bullet redBullet = BulletFactory.getBulletType(&quot;Red&quot;, &quot;HighRes_Laser_Texture.png&quot;);<br>        redBullet.render(10, 20, 300);<br>        redBullet.render(12, 22, 300);<br>        redBullet.render(15, 25, 300);<br><br>        // Player 2 fires 2 blue armor-piercing bullets<br>        Bullet blueBullet = BulletFactory.getBulletType(&quot;Blue&quot;, &quot;Heavy_AP_Texture.png&quot;);<br>        blueBullet.render(100, 200, 450);<br>        blueBullet.render(105, 205, 450);<br><br>        System.out.println(&quot;\n=== Memory Report ===&quot;);<br>        System.out.println(&quot;Total bullets fired: 5&quot;);<br>        System.out.println(&quot;Total distinct bullet objects stored in memory heap: &quot; + bulletCache.size());<br>    }<br>    <br>    // Simulating access to factory cache size for display<br>    private static final Map&lt;String, Bullet&gt; bulletCache = BulletFactory.getBulletType(&quot;Red&quot;, &quot;HighRes_Laser_Texture.png&quot;) != null ? reflectCache() : null;<br>    private static Map&lt;String, Bullet&gt; reflectCache() {<br>        try {<br>            java.lang.reflect.Field field = BulletFactory.class.getDeclaredField(&quot;bulletCache&quot;);<br>            field.setAccessible(true);<br>            return (Map&lt;String, Bullet&gt;) field.get(null);<br>        } catch(Exception e) { return new HashMap&lt;&gt;(); }<br>    }<br>}</pre><h3>1. The Interface Blueprint (Flyweight Interface)</h3><ul><li><strong>Parameter-Driven State:</strong> Notice how x, y, and speed are passed directly into the render() method rather than stored as fields inside the class.</li><li><strong>Enforced Statelessness:</strong> By declaring dynamic variables inside the method signature, the interface forces every implementing class to remain stateless regarding object coordinates and velocity.</li></ul><h3>2. The Heavy Asset Container (Concrete Flyweight)</h3><ul><li><strong>Intrinsic Encapsulation:</strong> Fields like color and texture are marked private final, ensuring that shared visual assets cannot be mutated by client calls once instantiated.</li><li><strong>One-Time Asset Initialization:</strong> The constructor simulates an expensive disk or GPU memory load operation. Because of the factory, this constructor executes <strong>only once per distinct bullet style</strong>, no matter how many millions of bullets are actively rendered on screen.</li></ul><h3>3. The Centralized Cache Manager (Flyweight Factory)</h3><ul><li><strong>Composite Key Indexing:</strong> The factory constructs a unique key combining color and texture strings (e.g., &quot;Red_HighRes_Laser_Texture.png&quot;).</li><li><strong>Cache Hit vs. Miss Routing:</strong> Upon receiving a request, the factory queries its internal HashMap:</li><li><strong>Cache Hit:</strong> Returns the existing object reference directly from heap RAM without creating a new object.</li><li><strong>Cache Miss:</strong> Instantiates the object once, saves it inside the map, and returns the newly cached reference.</li></ul><h3>4. The Client Execution &amp; Memory Heap Verification</h3><ul><li><strong>Decoupled Positioning:</strong> The main simulation manages the rapidly changing coordinates (x, y) and velocity of every active projectile, passing these values into the shared bullet instances at the moment of rendering.</li><li><strong>The Heap Proof:</strong> Even though the game fires 5 distinct projectiles with individual flight paths across the screen, the reflection output proves that <strong>only 2 unique objects</strong> ever exist on the JVM memory heap.</li></ul><p>“The brilliance of the Flyweight Pattern is that memory consumption scales with visual diversity O(K) , not entity volume O(N) . Moving dynamic coordinates to runtime arguments compresses your application’s heap footprint dramatically.”</p><h3>Key Takeaways</h3><ul><li><strong>Apply Only Under Heavy Memory Pressure:</strong> Flyweight is strictly an optimization pattern. Introduce it only when high object counts create measurable heap bloat or trigger frequent Garbage Collection pauses.</li><li><strong>Enforce Absolute Immutability:</strong> Intrinsic state stored inside the flyweight <strong>must</strong> be read-only (final in Java). If client code mutates intrinsic data, it inadvertently alters that state across every shared reference in the system.</li><li><strong>Memory vs. CPU Trade-off:</strong> Reducing RAM usage requires computing or passing extrinsic state into methods at runtime. Always verify that memory savings outweigh any minor CPU overhead caused by runtime context passing.</li><li><strong>Natural Pattern Pairings:</strong> Flyweight rarely exists alone — it relies on the <strong>Factory Pattern</strong> to handle cache management and encapsulation, and frequently pairs with the <strong>Composite Pattern</strong> to build complex visual component trees.</li></ul><h3>Real World Use Cases</h3><ul><li><strong>Java Language Internals (String Pool &amp; Integer Cache):</strong> Java automatically caches String literals and small integers ($-128$ to $127$). When you write &quot;hello&quot; multiple times across a codebase, Java returns identical memory addresses from the String Pool rather than allocating new heap memory every time.</li><li><strong>Game Engines (Tilemaps, Foliage &amp; Particle Systems):</strong> Engines like Unity or Unreal render millions of environmental assets (forest trees, rain drops, bullet sprays) using Flyweight principles. A single 3D mesh and texture are stored once in VRAM, while individual object positions, rotations, and scale values are passed dynamically to GPU draw calls.</li><li><strong>Text Editors &amp; Web Layout Engines:</strong> Browsers and word processors treat character glyphs as flyweights. Font geometries and kerning maps are parsed and cached once; individual font sizes, colors, and page coordinates are passed dynamically when rendering text on screen.</li><li><strong>UI Vector Icons (SVG Symbol Reuse):</strong> Web applications define reusable SVG icons once in an icon sprite or template pool. The browser loads the vector paths into memory once and applies custom dimensions, CSS colors, and DOM positions per instance.</li><li><strong>Database &amp; Network Connection Pools:</strong> Frameworks like HikariCP manage pool objects where core connection infrastructure (socket, authentication credentials) is shared, while session-specific transaction parameters are passed during active queries.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3770dab87236" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding the Proxy Design Pattern]]></title>
            <link>https://medium.com/@gupta_harshal/understanding-the-proxy-design-pattern-fa191d86f175?source=rss-43619e04b875------2</link>
            <guid isPermaLink="false">https://medium.com/p/fa191d86f175</guid>
            <category><![CDATA[low-level-design]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Harshal Gupta]]></dc:creator>
            <pubDate>Sun, 16 Aug 2026 00:04:06 GMT</pubDate>
            <atom:updated>2026-08-16T00:04:06.331Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>The <strong>Proxy Design Pattern</strong> is a structural pattern that provides a surrogate, placeholder, or intermediary for another object. Instead of the client interacting directly with the core service, it interacts with a <strong>Proxy object</strong>. This proxy controls access to the real object, allowing you to execute tasks like security checks, logging, lazy initialization, or caching before or after the request reaches the target.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/973/1*U-fGCnxqh2q6iq1YFutA0A.png" /></figure><p>Think of a corporate office network:</p><ul><li><strong>Real Subject:</strong> The unrestricted Global Internet infrastructure (heavy, open, direct access).</li><li><strong>Proxy:</strong> The Company Firewall.</li><li><strong>Client:</strong> An employee laptop inside the office.</li></ul><p>When an employee attempts to visit a website, they don’t route straight to the external server. They hit the company firewall first. If the URL is leetcode.com, the firewall passes the request through. If the URL is instagram.com, the firewall intercepts it, blocks execution, and throws an error without touching the external network.</p><h3>Code Sample</h3><pre>// 1. SUBJECT INTERFACE (The common blueprint shared by both the real object and the proxy)<br>interface Internet {<br>    void connectTo(String serverUrl) throws Exception;<br>}<br><br>// 2. REAL SUBJECT (The heavy, core service doing the actual network lifting)<br>class RealInternet implements Internet {<br>    @Override<br>    public void connectTo(String serverUrl) {<br>        System.out.println(&quot;Network: Establishing secure connection to -&gt; &quot; + serverUrl);<br>    }<br>}<br><br>// 3. PROXY (The gateway containing smart interception logic before hitting the real service)<br>class ProxyInternet implements Internet {<br>    private Internet realInternet = new RealInternet();<br>    private static java.util.List&lt;String&gt; bannedSites;<br><br>    static {<br>        bannedSites = new java.util.ArrayList&lt;&gt;();<br>        bannedSites.add(&quot;facebook.com&quot;);<br>        bannedSites.add(&quot;instagram.com&quot;);<br>        bannedSites.add(&quot;twitter.com&quot;);<br>    }<br><br>    @Override<br>    public void connectTo(String serverUrl) throws Exception {<br>        // Step A: Perform Access Control / Security Check<br>        if (bannedSites.contains(serverUrl.toLowerCase())) {<br>            throw new SecurityException(&quot;Access Denied: &#39;&quot; + serverUrl + &quot;&#39; is blacklisted on this corporate network!&quot;);<br>        }<br><br>        // Step B: If validations clear, forward the execution to the real object<br>        realInternet.connectTo(serverUrl);<br>    }<br>}<br><br>// 4. CLIENT CODE<br>public class Main {<br>    public static void main(String[] args) {<br>        // The client code interacts strictly via the abstract interface type<br>        Internet officeNetwork = new ProxyInternet();<br><br>        try {<br>            System.out.println(&quot;=== Test Case 1: Accessing educational resource ===&quot;);<br>            officeNetwork.connectTo(&quot;leetcode.com&quot;);<br><br>            System.out.println(&quot;\n=== Test Case 2: Accessing blacklisted domain ===&quot;);<br>            officeNetwork.connectTo(&quot;instagram.com&quot;);<br>            <br>        } catch (Exception e) {<br>            System.out.println(&quot;Proxy Interception Rule Triggered: &quot; + e.getMessage());<br>        }<br>    }<br>}</pre><h4>1. The Common Contract (Subject Interface)</h4><p>By defining a shared interface, both your proxy and the real object adhere to the exact same contract.</p><ul><li><strong>Polymorphic Interchangeability:</strong> Because the client code references the interface rather than a concrete class, you can swap out the real network layer for a proxy (or chain multiple proxies together) without breaking a single line of downstream client code.</li><li><strong>Behavior Isolation:</strong> It defines <strong>what</strong> the network capability is without dictating <strong>how</strong> security, logging, or connection handling should be executed.</li></ul><h4>2. The Core Service (Real Subject)</h4><p>This class serves as the heavy lifter responsible solely for establishing actual network connections.</p><ul><li><strong>Single Responsibility Principle (SRP):</strong> This class has zero knowledge of corporate blacklists, user roles, or firewall rules. Its only job is to handle the network payload.</li><li><strong>Decoupled Security:</strong> Keeping access control logic out of the core service ensures that network code remains clean, easy to test, and free of security-related clutter.</li></ul><h4>3. The Intermediary Gateway (Proxy)</h4><p>This acts as the gatekeeper. It wraps the core service inside itself and intercepts incoming requests before they reach the actual network execution layer.</p><ul><li><strong>Static Blacklist Initialization:</strong> A static collection holds restricted domain rules in memory, ensuring validation checks run instantly without hitting slow external databases on every call.</li><li><strong>Interception &amp; Guard Clause:</strong> When a request comes in, the proxy converts the target URL to lowercase and checks it against the blacklist. If a match is found, execution halts immediately by throwing a security exception. The underlying service is never invoked, saving system bandwidth and preventing unauthorized calls.</li><li><strong>Forward Delegation:</strong> If the domain passes validation, the proxy forwards execution to the real object to complete the connection.</li></ul><h4>4. The Client Execution</h4><p>The client orchestrates the calls through the shared interface reference.</p><ul><li><strong>Test Case 1 (Allowed Domain):</strong> Passing a clean domain like leetcode.com bypasses the guard clause, seamlessly delegating execution to the core network service and printing the connection message.</li><li><strong>Test Case 2 (Blacklisted Domain):</strong> Passing a blocked domain like instagram.com triggers the proxy’s security rule. The proxy aborts the request before touching the real network layer, allowing the client&#39;s error-handling block to catch and handle the interception gracefully.</li></ul><h3>Real World Use Cases</h3><h3>1. ORM Lazy Loading (e.g., Hibernate / Entity Framework)</h3><p>When fetching a User object from a database in an ORM, loading their entire OrderHistory immediately can crash server performance.</p><ul><li><strong>The Proxy at Work:</strong> The ORM returns a <strong>Virtual Proxy</strong> placeholder instead of querying millions of order records right away.</li><li><strong>Execution:</strong> The SQL query to fetch orders is only executed when your application explicitly calls user.getOrders().</li></ul><h3>2. Spring AOP (Aspect-Oriented Programming)</h3><p>In enterprise Java, adding @Transactional or @PreAuthorize(&quot;hasRole(&#39;ADMIN&#39;)&quot;) over a database or API method uses proxies under the hood.</p><ul><li><strong>The Proxy at Work:</strong> Spring wraps your class in a <strong>Dynamic Proxy</strong> at runtime.</li><li><strong>Execution:</strong> When a caller invokes your service method, the proxy intercepts the call, checks authentication roles, opens a database transaction, forwards execution to your real method, commits the transaction, and closes it transparently.</li></ul><h3>3. API Rate Limiting &amp; Gateway Firewalls (e.g., Kong / Nginx)</h3><p>API Gateways operate as <strong>Protection Proxies</strong> sitting in front of microservices.</p><ul><li><strong>The Proxy at Work:</strong> Before your payment microservice processes a charge, an API gateway proxy intercepts the HTTP request.</li><li><strong>Execution:</strong> It checks Redis to see if the client exceeded 100 requests per minute. If throttled, it rejects the request with a 429 Too Many Requests status code before touching the core payment microservice.</li></ul><h3>4. Caching Layers (e.g., Redis Client / CDN)</h3><p>High-traffic applications use <strong>Caching Proxies</strong> to prevent database overload.</p><ul><li><strong>The Proxy at Work:</strong> A database wrapper proxy intercepts read requests.</li><li><strong>Execution:</strong> If requested data lives in the local cache, the proxy returns it instantly without hitting the database. If missed, it queries the database, caches the result, and returns it for subsequent calls.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fa191d86f175" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding the Decorator Design Pattern]]></title>
            <link>https://medium.com/@gupta_harshal/understanding-the-decorator-design-pattern-2d523ddf956c?source=rss-43619e04b875------2</link>
            <guid isPermaLink="false">https://medium.com/p/2d523ddf956c</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[low-level-design]]></category>
            <dc:creator><![CDATA[Harshal Gupta]]></dc:creator>
            <pubDate>Thu, 06 Aug 2026 16:22:24 GMT</pubDate>
            <atom:updated>2026-08-06T16:22:24.665Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>The <strong>Decorator Design Pattern</strong> allows you to dynamically add new behaviors or responsibilities to an object at runtime without altering its original structure or modifying existing code.</blockquote><blockquote>Think of it like <strong>Russian nesting dolls</strong> or <strong>wrapping a gift</strong>: you start with a core object and wrap layer after layer around it. Each layer adds a new feature while still keeping the object looking like a “Coffee” from the outside.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/972/1*mb-y2-uAtGKR-LW_ySoxSA.png" /></figure><h3>Code Sample</h3><pre>// 1. COMPONENT INTERFACE (The base blueprint for core objects and decorators)<br>interface Coffee {<br>    String getDescription();<br>    double getCost();<br>}<br><br>// 2. CONCRETE COMPONENT (The basic object that can have responsibilities added to it)<br>class PlainCoffee implements Coffee {<br>    @Override<br>    public String getDescription() {<br>        return &quot;Plain Coffee&quot;;<br>    }<br><br>    @Override<br>    public double getCost() {<br>        return 50.0; // Base Price in INR<br>    }<br>}<br><br>// 3. BASE DECORATOR (Implements Component and wraps a Component instance via Composition)<br>abstract class CoffeeDecorator implements Coffee {<br>    protected Coffee decoratedCoffee; // The wrapped object<br><br>    public CoffeeDecorator(Coffee coffee) {<br>        this.decoratedCoffee = coffee;<br>    }<br><br>    @Override<br>    public String getDescription() {<br>        return decoratedCoffee.getDescription();<br>    }<br><br>    @Override<br>    public double getCost() {<br>        return decoratedCoffee.getCost();<br>    }<br>}<br><br>// 4. CONCRETE DECORATORS (Adding custom features/behaviors dynamically)<br>class MilkDecorator extends CoffeeDecorator {<br>    public MilkDecorator(Coffee coffee) {<br>        super(coffee);<br>    }<br><br>    @Override<br>    public String getDescription() {<br>        return super.getDescription() + &quot;, with Milk&quot;;<br>    }<br><br>    @Override<br>    public double getCost() {<br>        return super.getCost() + 15.0; // Adds price of milk<br>    }<br>}<br><br>class MochaDecorator extends CoffeeDecorator {<br>    public MochaDecorator(Coffee coffee) {<br>        super(coffee);<br>    }<br><br>    @Override<br>    public String getDescription() {<br>        return super.getDescription() + &quot;, with Mocha (Chocolate)&quot;;<br>    }<br><br>    @Override<br>    public double getCost() {<br>        return super.getCost() + 25.0; // Adds price of mocha<br>    }<br>}<br><br>// 5. CLIENT CODE<br>public class Main {<br>    public static void main(String[] args) {<br>        // Step A: Order a plain coffee<br>        Coffee myCoffee = new PlainCoffee();<br>        System.out.println(&quot;Order 1: &quot; + myCoffee.getDescription() + &quot; | Cost: ₹&quot; + myCoffee.getCost());<br><br>        // Step B: Wrap it with Milk at runtime<br>        myCoffee = new MilkDecorator(myCoffee);<br>        System.out.println(&quot;Order 2: &quot; + myCoffee.getDescription() + &quot; | Cost: ₹&quot; + myCoffee.getCost());<br><br>        // Step C: Wrap it again with Mocha chocolate layer<br>        myCoffee = new MochaDecorator(myCoffee);<br>        System.out.println(&quot;Order 3: &quot; + myCoffee.getDescription() + &quot; | Cost: ₹&quot; + myCoffee.getCost());<br>        <br>        // Notice how we didn&#39;t create a complex &quot;PlainCoffeeWithMilkAndMocha&quot; class!<br>    }<br>}</pre><h3>The Problem: “Class Explosion”</h3><p>Imagine you are building an order processing system for a coffee shop. You start with a base PlainCoffee class. Soon, customers start asking for add-ons:</p><ul><li>Milk</li><li>Mocha</li><li>Caramel</li><li>Whipped Cream</li></ul><p>If you rely purely on traditional inheritance, you would have to create a separate class for every single combination:</p><ul><li>CoffeeWithMilk</li><li>CoffeeWithMocha</li><li>CoffeeWithMilkAndMocha</li><li>CoffeeWithCaramelAndWhippedCream ...and so on.</li></ul><p>For N features, static inheritance requires up to 2^N distinct subclasses. This phenomenon is known as <strong>Class Explosion</strong>. It creates rigid, unmaintainable code that violates the core principles of object-oriented design.</p><h3>The Solution: Dynamic Wrapping</h3><p>The <strong>Decorator Pattern</strong> solves this problem using <strong>composition instead of inheritance</strong>.</p><p>Think of decorators like <strong>Russian nesting dolls</strong> or <strong>wrapping paper</strong>:</p><ol><li>You take a core object (PlainCoffee).</li><li>You wrap it inside a decorator layer (MilkDecorator).</li><li>You wrap that combined object inside another decorator layer (MochaDecorator).</li></ol><p>To the outside world, the final wrapped package still looks and behaves like a Coffee object. When a method like getCost() is called on the outermost layer, it triggers a chain reaction through each wrapper down to the base item, summing up the totals automatically.</p><pre>[ MochaDecorator ] ──wraps──&gt; [ MilkDecorator ] ──wraps──&gt; [ PlainCoffee ]</pre><h3>1. The Component Interface</h3><p>This is the unified contract implemented by both the base component and all decorators.</p><pre>public interface Coffee {<br>    String getDescription();<br>    double getCost();<br>}</pre><h3>2. The Concrete Component</h3><p>The base object that provides the foundational logic. It can exist entirely on its own.</p><pre>public class PlainCoffee implements Coffee {<br>    @Override<br>    public String getDescription() {<br>        return &quot;Plain Coffee&quot;;<br>    }<br>    @Override<br>    public double getCost() {<br>        return 50.0; // Base Price in INR<br>    }<br>}</pre><h3>3. The Abstract Decorator</h3><p>The structural bridge. It implements Coffee and holds a reference to a Coffee instance (<strong>composition</strong>).</p><pre>public abstract class CoffeeDecorator implements Coffee {<br>    protected Coffee decoratedCoffee; // Reference to the wrapped object<br>    public CoffeeDecorator(Coffee coffee) {<br>        this.decoratedCoffee = coffee;<br>    }<br>    @Override<br>    public String getDescription() {<br>        return decoratedCoffee.getDescription(); // Delegates call to wrapped instance<br>    }<br>    @Override<br>    public double getCost() {<br>        return decoratedCoffee.getCost(); // Delegates call to wrapped instance<br>    }<br>}</pre><h3>4. Concrete Decorators</h3><p>These classes extend CoffeeDecorator to dynamically add extra state or behavior.</p><pre>public class MilkDecorator extends CoffeeDecorator {<br>    public MilkDecorator(Coffee coffee) {<br>        super(coffee);<br>    }<br>    @Override<br>    public String getDescription() {<br>        return super.getDescription() + &quot;, with Milk&quot;;<br>    }<br>    @Override<br>    public double getCost() {<br>        return super.getCost() + 15.0; // Adds price of milk<br>    }<br>}<br>public class MochaDecorator extends CoffeeDecorator {<br>    public MochaDecorator(Coffee coffee) {<br>        super(coffee);<br>    }<br>    @Override<br>    public String getDescription() {<br>        return super.getDescription() + &quot;, with Mocha (Chocolate)&quot;;<br>    }<br>    @Override<br>    public double getCost() {<br>        return super.getCost() + 25.0; // Adds price of mocha<br>    }<br>}</pre><h3>5. Client Execution</h3><pre>public class Main {<br>    public static void main(String[] args) {<br>        // Step 1: Instantiate a plain coffee<br>        Coffee myCoffee = new PlainCoffee();<br>        System.out.println(myCoffee.getDescription() + &quot; | Cost: ₹&quot; + myCoffee.getCost());<br>        // Step 2: Wrap it with Milk at runtime<br>        myCoffee = new MilkDecorator(myCoffee);<br>        System.out.println(myCoffee.getDescription() + &quot; | Cost: ₹&quot; + myCoffee.getCost());<br>        // Step 3: Wrap it again with Mocha<br>        myCoffee = new MochaDecorator(myCoffee);<br>        System.out.println(myCoffee.getDescription() + &quot; | Cost: ₹&quot; + myCoffee.getCost());<br>    }<br>}</pre><h4>Console Output:</h4><pre>Plain Coffee | Cost: ₹50.0<br>Plain Coffee, with Milk | Cost: ₹65.0<br>Plain Coffee, with Milk, with Mocha (Chocolate) | Cost: ₹90.0</pre><h3>How the Code Executes Behind the Scenes</h3><p>When myCoffee.getCost() is called on the fully wrapped object, execution propagates down a recursive delegation stack:</p><pre>MochaDecorator.getCost()<br> └──&gt; Calls super.getCost() -&gt; MilkDecorator.getCost()<br>       └──&gt; Calls super.getCost() -&gt; PlainCoffee.getCost()<br>             └──&gt; Returns base price: 50.0<br>       ──&gt; Adds milk cost (+ 15.0) -&gt; Returns 65.0<br> ──&gt; Adds mocha cost (+ 25.0) -&gt; Returns 90.0</pre><h3>Why the Decorator Pattern Matters</h3><h3>1. Adheres to SOLID Principles</h3><ul><li><strong>Open/Closed Principle (OCP):</strong> You can add brand-new features (e.g., CaramelDecorator or WhippedCreamDecorator) by adding new classes without touching or risking existing code.</li><li><strong>Single Responsibility Principle (SRP):</strong> Rather than cluttering PlainCoffee with flags like hasMilk or hasMocha, each decorator class handles exactly one topping.</li></ul><h3>2. Replaces Exponential Growth with Linear Growth</h3><p>Instead of needing 2^N classes for all combinations, you only need N + 1 classes (1 base component + N decorator classes).</p><h3>3. Dynamic Runtime Customization</h3><p>In inheritance, object behavior is fixed at compile time. Decorators allow you to dynamically stack behaviors on demand at runtime depending on client inputs.</p><h3>Real-World Use Cases of the Decorator Pattern</h3><h3>1. Java I/O Streams (java.io)</h3><p>The standard Java library provides one of the most famous built-in implementations of the Decorator pattern. Reading a file in Java involves layering multiple stream implementations, where each layer decorates the underlying raw byte stream with new capabilities.</p><pre>InputStream fileStream = new FileInputStream(&quot;data.txt&quot;);          // Base: Reads raw bytes<br>InputStream bufferedStream = new BufferedInputStream(fileStream); // Decorator 1: Adds memory buffering<br>GZIPInputStream zipStream = new GZIPInputStream(bufferedStream);    // Decorator 2: Adds on-the-fly decompression</pre><p>Each wrapper implements the base InputStream abstract class. You can chain buffering, decryption, or decompression transparently without modifying how client code reads data.</p><h3>2. E-Commerce Pricing &amp; Checkout Engines</h3><p>Calculating the final total of a shopping cart during checkout involves dynamic pricing rules. Rather than building static classes like CartWithTaxAndCouponAndGiftWrap, e-commerce engines apply decorators dynamically based on user actions:</p><ul><li><strong>Base Component:</strong> StandardCart ($100.00)</li><li><strong>Decorator 1:</strong> DiscountCouponDecorator (Deducts 10% → $90.00)</li><li><strong>Decorator 2:</strong> TaxDecorator (Adds 8% state tax → $97.20)</li><li><strong>Decorator 3:</strong> GiftWrapDecorator (Adds flat $5.00 fee → $102.20)</li></ul><p>When cart.calculateTotal() executes, the invocation cascades down the wrapper chain, applying each pricing rule sequentially.</p><h3>3. Web Middleware &amp; Request Pipelines</h3><p>Modern web frameworks (Express.js, Go net/http, ASP.NET Core) structure HTTP request handlers using middleware chains, which are a functional variant of the Decorator pattern.</p><p>When an HTTP request hits the server, it passes through a stack of nested wrappers before reaching the core endpoint handler:</p><pre>HTTP Request <br>  └──&gt; LoggerMiddleware (Logs request metadata)<br>        └──&gt; AuthMiddleware (Validates JWT tokens)<br>              └──&gt; RateLimitMiddleware (Checks request quota)<br>                    └──&gt; UserController (Executes core business logic)</pre><p>If authentication or rate-limiting fails at a wrapper layer, execution halts early before ever reaching the database or controller.</p><h3>4. Game Development (Buffs, Debuffs, &amp; Equipment)</h3><p>In RPG game engines, entity attributes (attack power, movement speed, defense) change constantly due to temporary spells, potions, or equipped gear.</p><ul><li><strong>Base Entity:</strong> Knight (Base Attack: 50)</li><li><strong>Equipped Weapon:</strong> FireSwordDecorator (Adds +20 Fire Damage)</li><li><strong>Active Buff:</strong> BerserkRageDecorator (Multiplies total damage by 1.5×)</li><li><strong>Active Debuff:</strong> PoisonDecorator (Reduces defense by 10%)</li></ul><p>Calling player.getAttackDamage() calculates (50+20)×1.5=105 dynamically. When the temporary BerserkRage buff timer expires, the game loop un-wraps that specific decorator layer without affecting the base Knight object or its equipped weapon.</p><h3>5. Microservice Resilience &amp; Fault Tolerance</h3><p>When microservices communicate over network boundaries, calls require safeguards like retries, circuit breakers, and rate limiters. Resilience libraries like <strong>Resilience4j</strong> use decorators to compose these policies around raw network calls:</p><pre>// 1. Base HTTP API Call<br>Supplier&lt;String&gt; restApiCall = () -&gt; httpClient.get(&quot;https://api.stripe.com/v1/charges&quot;);<br>// 2. Decorate with Rate Limiting (Max 10 requests/sec)<br>Supplier&lt;String&gt; rateLimitedCall = RateLimiter.decorateSupplier(rateLimiter, restApiCall);<br>// 3. Decorate with Retry Logic (Retry up to 3 times on network failure)<br>Supplier&lt;String&gt; resilientCall = Retry.decorateSupplier(retryConfig, rateLimitedCall);<br>// Execute the call with all protection layers active<br>String response = resilientCall.get();</pre><h3>6. GUI Toolkit Extensions</h3><p>Graphical User Interface (GUI) frameworks use decorators to add visual adornments or interactive capabilities to base UI components without altering the underlying widget class:</p><ul><li><strong>Base Component:</strong> TextView (Renders raw text)</li><li><strong>Decorator 1:</strong> ScrollbarDecorator (Wraps TextView in vertical/horizontal scrollbars when content overflows)</li><li><strong>Decorator 2:</strong> BorderDecorator (Draws a custom drop-shadow border around the view)</li></ul><p>This is seen in Java Swing with JScrollPane:</p><pre>JTextArea textArea = new JTextArea(10, 30);<br>JScrollPane scrollPane = new JScrollPane(textArea); // Decorates JTextArea with scrolling capabilities</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2d523ddf956c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding the Facade Design Pattern]]></title>
            <link>https://medium.com/@gupta_harshal/understanding-the-facade-design-pattern-0c9dbaa7d80a?source=rss-43619e04b875------2</link>
            <guid isPermaLink="false">https://medium.com/p/0c9dbaa7d80a</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[low-level-design]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Harshal Gupta]]></dc:creator>
            <pubDate>Wed, 05 Aug 2026 17:15:22 GMT</pubDate>
            <atom:updated>2026-08-05T17:15:22.868Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>Imagine walking into a high-end home theater setup. You have a projector, an AV receiver, a surround sound system, and a streaming media player. To watch a single movie, you have to find four different remotes, power on every device individually, switch the projector to widescreen, configure the audio output to Dolby Atmos, set the amplifier volume, and launch the streaming app.</blockquote><blockquote>It works, but it’s tedious, error-prone, and frustrating.</blockquote><blockquote>Now imagine pressing a single button labeled <strong>“Watch Movie”</strong> on a unified smart remote that handles all those steps automatically in the background.</blockquote><blockquote>In software engineering, that smart remote is called the <strong>Facade Design Pattern</strong>.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*QtW2a9Xc1qPxZz_3WYHheg.png" /></figure><h3>What is the Facade Pattern?</h3><p>The <strong>Facade Pattern</strong> is a structural design pattern that provides a simplified, higher-level interface to a complex subsystem of classes, library, or framework.</p><p>Instead of forcing client code to interact with dozens of low-level methods across multiple objects, a Facade exposes a few clean, macro-level operations. It doesn’t hide or disable the underlying subsystem — it simply offers a convenient shortcut for the most common use cases.</p><h3>The Problem: Subsystem Complexity</h3><p>Without a Facade, the client code must instantiate and orchestrate every subsystem directly:</p><pre>// Client code without Facade (Messy, tightly coupled)<br>Amplifier amp = new Amplifier();<br>Projector projector = new Projector();<br>SoundSystem sound = new SoundSystem();<br>StreamingService streaming = new StreamingService();<br>projector.turnOn();<br>projector.setWideScreenMode();<br>amp.turnOn();<br>amp.setVolume(12);<br>sound.enableSurroundSound();<br>streaming.playMovie(&quot;Inception&quot;);</pre><h3>Why this is problematic:</h3><ol><li><strong>High Coupling:</strong> The client must know intimate details about Amplifier, Projector, SoundSystem, and StreamingService.</li><li><strong>Code Duplication:</strong> Every place in your application that needs to start a movie must repeat this exact sequence.</li><li><strong>Maintenance Risk:</strong> If the initialization sequence changes (e.g., sound must be enabled <em>before</em> turning on the amplifier), every client call site breaks.</li></ol><h3>Code Walkthrough</h3><pre>// 1. COMPLEX SUBSYSTEMS (Classes with varied, low-level operational methods)<br>class Amplifier {<br>    public void turnOn() { System.out.println(&quot;Amplifier: Powering ON.&quot;); }<br>    public void setVolume(int level) { System.out.println(&quot;Amplifier: Volume set to &quot; + level); }<br>    public void turnOff() { System.out.println(&quot;Amplifier: Powering OFF.&quot;); }<br>}<br><br>class Projector {<br>    public void turnOn() { System.out.println(&quot;Projector: Powering ON.&quot;); }<br>    public void setWideScreenMode() { System.out.println(&quot;Projector: Screen aspect ratio set to 16:9.&quot;); }<br>    public void turnOff() { System.out.println(&quot;Projector: Powering OFF.&quot;); }<br>}<br><br>class SoundSystem {<br>    public void enableSurroundSound() { System.out.println(&quot;Sound System: Dolby Atmos Surround enabled.&quot;); }<br>}<br><br>class StreamingService {<br>    public void playMovie(String movie) { System.out.println(&quot;Streaming Service: Buffering and streaming &#39;&quot; + movie + &quot;&#39;...&quot;); }<br>}<br><br>// 2. FACADE (The unified class that wraps complex subsystems into simple methods)<br>class HomeTheaterFacade {<br>    private Amplifier amp;<br>    private Projector projector;<br>    private SoundSystem sound;<br>    private StreamingService streaming;<br><br>    // Subsystems are passed into the facade via composition<br>    public HomeTheaterFacade(Amplifier amp, Projector projector, SoundSystem sound, StreamingService streaming) {<br>        this.amp = amp;<br>        this.projector = projector;<br>        this.sound = sound;<br>        this.streaming = streaming;<br>    }<br><br>    // A single, high-level method hiding massive internal multi-step logic<br>    public void watchMovie(String movie) {<br>        System.out.println(&quot;\n--- Initializing Movie Mode ---&quot;);<br>        projector.turnOn();<br>        projector.setWideScreenMode();<br>        amp.turnOn();<br>        amp.setVolume(12);<br>        sound.enableSurroundSound();<br>        streaming.playMovie(movie);<br>        System.out.println(&quot;--- System Ready. Enjoy your show! ---\n&quot;);<br>    }<br><br>    public void endMovie() {<br>        System.out.println(&quot;\n--- Shutting Down System ---&quot;);<br>        streaming.playMovie(&quot;&quot;); // Stops streaming<br>        amp.turnOff();<br>        projector.turnOff();<br>        System.out.println(&quot;--- System Safely Powered Down ---\n&quot;);<br>    }<br>}<br><br>// 3. CLIENT<br>public class Main {<br>    public static void main(String[] args) {<br>        // Instantiate the complex subsystem parts<br>        Amplifier amp = new Amplifier();<br>        Projector projector = new Projector();<br>        SoundSystem sound = new SoundSystem();<br>        StreamingService streaming = new StreamingService();<br><br>        // Pass them into the Facade<br>        HomeTheaterFacade homeTheater = new HomeTheaterFacade(amp, projector, sound, streaming);<br><br>        // The client interacts only with the simplified Facade interface<br>        homeTheater.watchMovie(&quot;Inception&quot;);<br>        <br>        // Easily shut everything down with one call<br>        homeTheater.endMovie();<br>    }<br>}</pre><p>By introducing a HomeTheaterFacade, we wrap all low-level operational calls into simple, high-level methods: watchMovie() and endMovie().</p><p>To understand the mechanics of the Facade pattern, look at the three distinct layers in the implementation:</p><ol><li><strong>Subsystem Isolation (</strong><strong>Amplifier, </strong><strong>Projector, etc.):</strong> Each hardware component manages its own single responsibility without knowing the other components exist. They contain fine-grained methods like setWideScreenMode() or enableSurroundSound().</li><li><strong>Composition in the Facade (</strong><strong>HomeTheaterFacade):</strong> Instead of using inheritance, the Facade holds references to all subsystem objects via private fields. Passing these dependencies into the Facade’s constructor allows flexibility (dependency injection) while encapsulating their orchestration.</li><li><strong>Macro Operations (</strong><strong>watchMovie and </strong><strong>endMovie):</strong> The Facade methods act as high-level scripts. When the client calls watchMovie(&quot;Inception&quot;), the Facade executes six distinct low-level operations in the exact sequence required for the system to function correctly. The client only sees a single clean function call.</li></ol><h3>Real-World Use Cases</h3><h3>1. Database Connections &amp; ORMs (e.g., Hibernate / JPA)</h3><p>Opening a relational database connection natively requires configuring drivers, establishing socket connections, managing transactions, opening sessions, and handling raw SQL syntax. ORM frameworks provide a Facade layer (like EntityManager.persist() or session.save()) that abstracts away low-level connection pooling and SQL generation into simple object references.</p><h3>2. Spring Framework’s RestTemplate / WebClient</h3><p>Making a raw HTTP call in Java involves managing TCP connections, setting headers, serializing JSON payloads, reading input streams, and handling status codes. Spring’s RestTemplate or WebClient acts as a Facade, reducing a multi-step API call down to a single line:</p><p>Java</p><pre>User user = restTemplate.getForObject(&quot;https://api.example.com/users/1&quot;, User.class);</pre><h3>3. Payment Gateway Integrations (Stripe / PayPal APIs)</h3><p>Processing a payment under the hood requires verifying payment methods, checking risk metrics, converting currencies, capturing funds, and generating invoice records. Payment SDKs hide these separate API endpoints behind a single Facade call like Stripe.charge.create(params), allowing developers to process payments without writing complex multi-endpoint orchestration logic.</p><h3>4. Media Processing Libraries (FFmpeg Wrappers)</h3><p>FFmpeg is a powerful command-line tool for video processing, but using its low-level C API directly requires managing memory frames, audio streams, codecs, and container formats. Higher-level language wrappers expose simple Facade interfaces like VideoConverter.convert(input, output, &quot;MP4&quot;), hiding hundreds of lines of complex C code behind one method.</p><p>I hope that people reading this can easily understand and implement the Facade Design Pattern.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0c9dbaa7d80a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Composite Design Pattern: Developing the right intuition]]></title>
            <link>https://medium.com/@gupta_harshal/composite-design-pattern-developing-the-right-intuition-176c39d4acdc?source=rss-43619e04b875------2</link>
            <guid isPermaLink="false">https://medium.com/p/176c39d4acdc</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[low-level-design]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Harshal Gupta]]></dc:creator>
            <pubDate>Mon, 03 Aug 2026 18:46:24 GMT</pubDate>
            <atom:updated>2026-08-03T18:46:24.737Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>The <strong>Composite Design Pattern</strong> is a structural design pattern that lets you compose objects into <strong>tree structures</strong> to represent part-whole hierarchies.</blockquote><blockquote>Its main power is <strong>uniformity</strong>: it lets clients treat individual objects (like a single file) and compositions of objects (like a folder containing 50 files) <strong>identically</strong>.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FQjxYG1frO_hv_ndnxgz-Q.png" /></figure><h3>The Real-World Problem It Solves</h3><p>Think about how a file system on your computer works:</p><ul><li>A <strong>File</strong> takes up disk space.</li><li>A <strong>Folder</strong> contains files and <em>other folders</em>, and its total size is the sum of everything inside it.</li></ul><p>Without the Composite pattern, if you wanted to get the size of an item, you’d have to write clunky if-else checks:</p><pre>// BAD APPROACH (Without Composite Pattern)<br>if (item is File) {<br>    return item.getSize();<br>} else if (item is Directory) {<br>    // Write a complex loop to dig into sub-folders...<br>}</pre><p>The Composite pattern eliminates this mess completely. The client code doesn’t care if it’s talking to a single file or a deeply nested root folder — it calls .getSize() or .showDetails(), and it &quot;just works.&quot;</p><h3>Code Walkthrough</h3><pre>import java.util.ArrayList;<br>import java.util.List;<br><br>// 1. COMPONENT (The uniform interface for both individual and group objects)<br>interface FileSystemComponent {<br>    void showDetails(String indent);<br>    long getSize();<br>}<br><br>// 2. LEAF (Individual atomic objects that have no children)<br>class File implements FileSystemComponent {<br>    private String name;<br>    private long size;<br><br>    public File(String name, long size) {<br>        this.name = name;<br>        this.size = size;<br>    }<br><br>    @Override<br>    public void showDetails(String indent) {<br>        System.out.println(indent + &quot;- File: &quot; + name + &quot; (&quot; + size + &quot; KB)&quot;);<br>    }<br><br>    @Override<br>    public long getSize() {<br>        return this.size;<br>    }<br>}<br><br>// 3. COMPOSITE (Group objects that store references to other Components)<br>class Directory implements FileSystemComponent {<br>    private String name;<br>    private List&lt;FileSystemComponent&gt; components = new ArrayList&lt;&gt;();<br><br>    public Directory(String name) {<br>        this.name = name;<br>    }<br><br>    public void addComponent(FileSystemComponent component) {<br>        components.add(component);<br>    }<br><br>    public void removeComponent(FileSystemComponent component) {<br>        components.remove(component);<br>    }<br><br>    @Override<br>    public void showDetails(String indent) {<br>        System.out.println(indent + &quot;+ Directory: &quot; + name);<br>        for (FileSystemComponent component : components) {<br>            // Recursively trigger the same method down the tree structure<br>            component.showDetails(indent + &quot;  &quot;);<br>        }<br>    }<br><br>    @Override<br>    public long getSize() {<br>        long totalSize = 0;<br>        for (FileSystemComponent component : components) {<br>            totalSize += component.getSize();<br>        }<br>        return totalSize;<br>    }<br>}<br><br>// 4. CLIENT<br>public class Main {<br>    public static void main(String[] args) {<br>        // Individual files (Leafs)<br>        File file1 = new File(&quot;SOP.pdf&quot;, 465);<br>        File file2 = new File(&quot;AdapterPattern.java&quot;, 12);<br>        File file3 = new File(&quot;Avatar.mp4&quot;, 2500000);<br><br>        // Sub-directory<br>        Directory subDir = new Directory(&quot;College_Prep&quot;);<br>        subDir.addComponent(file1);<br>        subDir.addComponent(file2);<br><br>        // Root directory containing files and the sub-directory<br>        Directory rootDir = new Directory(&quot;Root&quot;);<br>        rootDir.addComponent(file3);<br>        rootDir.addComponent(subDir); // Composite inside Composite<br><br>        // Treat individual and composite objects identically via the interface<br>        System.out.println(&quot;=== Displaying Directory Tree ===&quot;);<br>        rootDir.showDetails(&quot;&quot;);<br><br>        System.out.println(&quot;\n=== Total Size Calculation ===&quot;);<br>        System.out.println(&quot;Total Space Used: &quot; + rootDir.getSize() + &quot; KB&quot;);<br>    }<br>}</pre><h3>1. The Component (FileSystemComponent)</h3><p>The interface acts as a <strong>contract</strong>. Both individual files and container directories implement FileSystemComponent. This forces both types to expose the exact same core actions: getSize() and showDetails().</p><h3>2. The Leaf (File)</h3><p>The File class represents end-node objects that <strong>cannot hold children</strong>.</p><ul><li>When getSize() is called on a File, it simply returns its own size (this.size).</li></ul><h3>3. The Composite (Directory)</h3><p>The Directory class represents container objects that <strong>hold a list of components</strong> (List&lt;FileSystemComponent&gt;).</p><ul><li>Because the list stores FileSystemComponent types, a Directory can hold <strong>both</strong> simple File objects and nested Directory objects.</li><li><strong>The Magic (Recursion):</strong> When rootDir.getSize() is called, the Directory loops through its items and calls .getSize() on each one. If an item is another Directory, it calls .getSize() on <em>its</em> children. The size automatically <strong>bubbles up</strong> through the tree without requiring complex conditional checks.</li></ul><h3>4. The Client (Main)</h3><p>The client code doesn’t need to know whether an element is a single file or a folder containing 10,000 sub-items. It calls rootDir.getSize() or rootDir.showDetails(&quot;&quot;), and the polymorphism + recursion handles the rest.</p><h3>Key Advantages</h3><ul><li><strong>Uniform Code Execution:</strong> Simplifies client logic by treating leaf elements and composite containers identically.</li><li><strong>Ease of Extension (Open/Closed Principle):</strong> You can add new leaf components (e.g., Shortcut, Symlink) without altering existing directory or client code.</li><li><strong>Natural Representation:</strong> Perfect for hierarchical, tree-based domain structures like file systems, GUI component trees, or corporate organizational charts.</li></ul><h3>Real-World Use Cases of the Composite Pattern</h3><p>You encounter the Composite pattern every day in modern software applications. Here are the most common real-world scenarios where it is used:</p><h3>1. Graphical User Interface (GUI) Frameworks</h3><p>Almost every modern UI framework (like Swing, React, Flutter, or Android XML views) uses the Composite pattern to build layout trees.</p><ul><li><strong>Component:</strong> UIElement / View (defines methods like draw(), getBounds())</li><li><strong>Leaf:</strong> Button, Label, TextField, Image</li><li><strong>Composite:</strong> Panel, Grid, StackLayout (containers holding child components)</li></ul><blockquote><strong><em>How it works:</em></strong><em> When the OS needs to render a screen, it calls </em><em>render() on the root layout panel. That panel automatically delegates </em><em>render() down to all its child buttons, text fields, and nested sub-panels.</em></blockquote><h3>2. Document Structure &amp; DOM (Document Object Model)</h3><p>Web browsers parse HTML pages into a tree structure known as the DOM.</p><ul><li><strong>Component:</strong> Node (defines methods like render(), getAttribute())</li><li><strong>Leaf:</strong> TextNode, ImageNode, InputNode</li><li><strong>Composite:</strong> &lt;div&gt;, &lt;p&gt;, &lt;ul&gt;, &lt;body&gt;</li></ul><blockquote><strong><em>How it works:</em></strong><em> Browsers apply CSS styles or JavaScript operations recursively across the DOM tree using the unified </em><em>Node interface.</em></blockquote><h3>3. Corporate Organizational Charts</h3><p>HR and enterprise management software use the Composite pattern to represent company hierarchies.</p><ul><li><strong>Component:</strong> CompanyMember (defines getSalary(), getReportCount())</li><li><strong>Leaf:</strong> Developer, Designer, QA Engine (individual employees)</li><li><strong>Composite:</strong> Manager, DepartmentHead, VP (employees who manage teams of other employees)</li></ul><blockquote><strong><em>How it works:</em></strong><em> Calling </em><em>manager.getBudget() recursively sums up the salary and expense budgets of every direct report and sub-team beneath that manager.</em></blockquote><h3>4. Graphic Design &amp; Vector Software (Photoshop, Illustrator, Figma)</h3><p>Design apps let users group multiple visual elements together.</p><ul><li><strong>Component:</strong> Graphic (defines draw(), rotate(), move())</li><li><strong>Leaf:</strong> Circle, Rectangle, Path</li><li><strong>Composite:</strong> Group (a collection of shapes or sub-groups)</li></ul><blockquote><strong><em>How it works:</em></strong><em> Selecting a “Group” and dragging it moves every individual shape inside that group smoothly without needing special code for multi-object handling.</em></blockquote><h3>5. E-Commerce Product Bundles &amp; Pricing Systems</h3><p>Online stores often sell single products alongside bundled packages.</p><ul><li><strong>Component:</strong> OrderableItem (defines getPrice())</li><li><strong>Leaf:</strong> SingleProduct (e.g., a $15 T-Shirt)</li><li><strong>Composite:</strong> ProductBundle (e.g., a &quot;Summer Starter Pack&quot; containing 2 T-shirts, 1 pair of shorts, and a cap at a discounted total)</li></ul><p><strong><em>How it works:</em></strong><em> The shopping cart treats both individual items and complex bundles identically when calculating sub-totals and applying discounts.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=176c39d4acdc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding the Adapter Design Pattern]]></title>
            <link>https://medium.com/@gupta_harshal/understanding-the-adapter-design-pattern-d13d6d988f99?source=rss-43619e04b875------2</link>
            <guid isPermaLink="false">https://medium.com/p/d13d6d988f99</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[low-level-design]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[design-patterns]]></category>
            <dc:creator><![CDATA[Harshal Gupta]]></dc:creator>
            <pubDate>Mon, 03 Aug 2026 18:22:08 GMT</pubDate>
            <atom:updated>2026-08-03T18:22:08.519Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>The <strong>Adapter Design Pattern</strong> is a structural design pattern that acts as a bridge between two incompatible interfaces. It allows objects with incompatible types to collaborate without altering their existing source code.</blockquote><blockquote>Think of it like a real-world <strong>travel adapter</strong>: If you take an Indian or European electrical plug to the US, it won’t fit into the wall socket. You don’t rewrite the US power grid, nor do you rewire your laptop charger — you just put an adapter in between.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AXUwFWadL7YVF3EA5OHtDA.png" /></figure><h3><strong>Code Walkthrough</strong></h3><pre>// 1. TARGET INTERFACE (What your application expects)<br>interface JsonPrinter {<br>    void printJson(String jsonData);<br>}<br><br>// 2. ADAPTEE (The incompatible third-party library you want to use)<br>class AdvancedXmlPrinter {<br>    public void printXml(String xmlData) {<br>        System.out.println(&quot;Printing XML Data securely: &quot; + xmlData);<br>    }<br>}<br><br>// 3. ADAPTER (The middleman translating JSON to XML)<br>class JsonToXmlAdapter implements JsonPrinter {<br>    private AdvancedXmlPrinter xmlPrinter;<br><br>    // Pass the incompatible object via constructor<br>    public JsonToXmlAdapter(AdvancedXmlPrinter xmlPrinter) {<br>        this.xmlPrinter = xmlPrinter;<br>    }<br><br>    @Override<br>    public void printJson(String jsonData) {<br>        // Step A: Convert JSON string to XML string (Simulated logic)<br>        String convertedXml = &quot;&lt;xml&gt;&quot; + jsonData.replace(&quot;{&quot;, &quot;&quot;).replace(&quot;}&quot;, &quot;&quot;) + &quot;&lt;/xml&gt;&quot;;<br>        <br>        // Step B: Delegate the work to the XML printer<br>        xmlPrinter.printXml(convertedXml);<br>    }<br>}<br><br>// 4. CLIENT (Your main application execution)<br>public class Main {<br>    public static void main(String[] args) {<br>        // Existing legacy setup or 3rd party tool<br>        AdvancedXmlPrinter thirdPartyPrinter = new AdvancedXmlPrinter();<br>        <br>        // Wrap it inside our Adapter<br>        JsonPrinter adapter = new JsonToXmlAdapter(thirdPartyPrinter);<br>        <br>        // The client code stays clean and uses the interface it expects<br>        String clientJsonData = &quot;{&#39;user&#39;: &#39;Harshal&#39;, &#39;status&#39;: &#39;Coding&#39;}&quot;;<br>        adapter.printJson(clientJsonData);<br>    }<br>}</pre><p>Imagine your application’s core system is designed to work strictly with <strong>JSON data</strong> through a standard contract (JsonPrinter).</p><p>Now, your company purchases a high-security, top-tier <strong>3rd-party library</strong> (AdvancedXmlPrinter). It&#39;s fast, encrypted, and feature-packed, but it has one major flaw: <strong>it only accepts XML data.</strong></p><h4>Why not just edit the 3rd-party code?</h4><ol><li><strong>No Source Access:</strong> You often don’t own the 3rd-party library code (it’s inside a .jar or npm package).</li><li><strong>Open-Closed Principle Violation:</strong> Modifying production-ready code every time an interface changes risks breaking existing features.</li><li><strong>Tight Coupling:</strong> Forcing your client code to handle XML logic pollutes your clean application design.</li></ol><p>Instead of changing either system, you build a wrapper class — the <strong>Adapter</strong>. The Adapter implements the interface your client expects (JsonPrinter) and internally holds an instance of the class you want to use (AdvancedXmlPrinter).</p><p>It helps us by the following ways:-</p><ul><li><strong>Single Responsibility Principle (SRP):</strong> Data conversion logic is isolated inside the Adapter, keeping your business logic clean.</li><li><strong>Open/Closed Principle (OCP):</strong> You can introduce new types of Adapters (e.g., JsonToYamlAdapter) without touching existing client code.</li><li><strong>Reusability:</strong> You can reuse legacy/3rd-party code in modern systems without rewriting it from scratch.</li></ul><h3>Real-World Examples in Software Engineering</h3><p>The Adapter Pattern is not just theoretical; you likely use it daily without realizing it. Here are four common scenarios:</p><h4>1. Cross-Platform UI Frameworks (like Flutter or React Native)</h4><p>When you write code in Flutter, you use a button component. However, when the app runs on <strong>iOS</strong>, it must render a <strong>CupertinoButton</strong>. When it runs on <strong>Android</strong>, it must render a <strong>MaterialButton</strong>.</p><p>The framework developers don’t make you write if (platform == iOS) { renderCupertino }. Instead, they create a target button interface. They then create adapters (like a MaterialButtonAdapter) that wrap the native OS-specific button and map the framework’s generic onPressed() call to the native onTap() or onClick() event.</p><h4>2. Logging Facades (e.g., SLF4J in Java)</h4><p>In the Java ecosystem, there are many logging libraries: java.util.logging, log4j, logback, and tinylog. If you write a library and hardcode it to use log4j, but the application consuming your library uses logback, conflicts arise.</p><p><strong>SLF4J (Simple Logging Facade for Java)</strong> solves this. It provides a standard Target Interface (Logger.info()). SLF4J then provides different <strong>Adapters</strong> (called &quot;bindings&quot;) for each logging library. If the application has the slf4j-log4j12.jar Adapter in its classpath, SLF4J translates the standard info() call into the log4j-specific logging method automatically.</p><h4>3. Database Drivers (JDBC/ODBC)</h4><p>Imagine writing software where every query had to be customized because MySQL uses slightly different syntax than PostgreSQL or Oracle.</p><p>Modern applications use a unified <strong>Target Interface</strong> (like JDBC in Java or PDO in PHP). When you want to connect to a MySQL database, you add the MySQL JDBC <strong>Driver</strong> (the Adapter). This driver knows exactly how to translate generic JDBC calls (like con.createStatement()) into the network protocol and SQL variant that MySQL understands. If you swap MySQL for PostgreSQL, you just swap the Adapter (the Driver); your application code remains unchanged.</p><h4>4. Payment Gateway Integration</h4><p>This is a classic e-commerce example. When building a checkout system, you define your internal Target Interface for processing payments:</p><pre>interface PaymentProcessor {<br>    void processPayment(double amount, String currency, String cardToken);<br>}</pre><p>If you start by integrating <strong>Stripe</strong>, you realize Stripe’s SDK doesn’t have a processPayment method. Instead, it has a complex flow involving PaymentIntent.create(params).</p><p>You create a <strong>StripeAdapter</strong>:</p><ul><li><strong>Its interface:</strong> PaymentProcessor.</li><li><strong>The wrapped object:</strong> Stripe SDK.</li><li><strong>The translation:</strong> It maps your simple processPayment(10.00, &quot;USD&quot;, &quot;tok_abc&quot;) call into the complex API parameters the Stripe SDK demands. This allows you to add <strong>PayPal</strong>, <strong>Braintree</strong>, or <strong>Adyen</strong> later by simply creating new Adapters.</li></ul><p>I hope this article helps the readers in understanding this design pattern and help them in their day to day lives.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d13d6d988f99" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[LLD Patterns: Memento Design Pattern]]></title>
            <link>https://medium.com/@gupta_harshal/lld-patterns-memento-design-pattern-c2c67363f6cc?source=rss-43619e04b875------2</link>
            <guid isPermaLink="false">https://medium.com/p/c2c67363f6cc</guid>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Harshal Gupta]]></dc:creator>
            <pubDate>Sun, 02 Aug 2026 18:08:06 GMT</pubDate>
            <atom:updated>2026-08-02T18:08:06.031Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>Memento Design Patterns is one of the Behavioral Design Patterns which is used to kind of capture a snapshot or we can say it is used to <strong>capture and restore an object’s internal state without exposing its internal implementation details</strong> (i.e., maintaining encapsulation).</blockquote><blockquote>Think of it as the ultimate <strong>“Ctrl + Z” (Undo/Redo)</strong> or <strong>“Save Point”</strong> pattern.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/768/1*CT2f1Sf09JuvySskO9JG1A.png" /></figure><h3>The Fundamental Problem Being Solved</h3><p>Normally, to save an object’s state (like a text editor’s string or cursor position), you would have to make its private variables public so an external History class can read and save them.</p><p>Doing this <strong>destroys encapsulation</strong> — it exposes internal implementation details to the rest of your app. If you ever change how the editor stores text internally, you break every class reading that state.</p><h3>Code</h3><pre>import java.util.Stack;<br><br>// 1. The Memento Object (Immutable snapshot box containing the saved state)<br>class EditorMemento {<br>    private final String content; // Marked final to ensure immutability<br><br>    public EditorMemento(String content) {<br>        this.content = content;<br>    }<br><br>    // Package-private access so only the TextEditor can read this value<br>    protected String getContent() {<br>        return content;<br>    }<br>}<br><br>// 2. The Originator (The main object whose state needs tracking/restoring)<br>class TextEditor {<br>    private String content = &quot;&quot;;<br><br>    public void type(String text) {<br>        content += text;<br>    }<br><br>    public String getContent() {<br>        return content;<br>    }<br><br>    // Creates a new snapshot checkpoint<br>    public EditorMemento save() {<br>        System.out.println(&quot;[Saving State]: \&quot;&quot; + content + &quot;\&quot;&quot;);<br>        return new EditorMemento(content);<br>    }<br><br>    // Restores state back from a specific memento instance<br>    public void restore(EditorMemento memento) {<br>        if (memento != null) {<br>            this.content = memento.getContent();<br>            System.out.println(&quot;[Restored State]: \&quot;&quot; + content + &quot;\&quot;&quot;);<br>        }<br>    }<br>}<br><br>// 3. The Caretaker (Manages the history stack of checkpoints; never alters snapshots)<br>class HistoryTracker {<br>    private final Stack&lt;EditorMemento&gt; history = new Stack&lt;&gt;();<br><br>    public void push(EditorMemento memento) {<br>        history.push(memento);<br>    }<br><br>    public EditorMemento pop() {<br>        if (!history.isEmpty()) {<br>            return history.pop();<br>        }<br>        System.out.println(&quot;No history states left to undo.&quot;);<br>        return null;<br>    }<br>}<br><br>// 4. Execution Driver<br>public class Main {<br>    public static void main(String[] args) {<br>        TextEditor editor = new TextEditor();<br>        HistoryTracker history = new HistoryTracker();<br><br>        // 1. User starts typing text<br>        editor.type(&quot;Design &quot;);<br>        history.push(editor.save()); // Save checkpoint 1<br><br>        // 2. User types more text<br>        editor.type(&quot;Patterns &quot;);<br>        history.push(editor.save()); // Save checkpoint 2<br><br>        // 3. User makes a typing mistake<br>        editor.type(&quot;are completely boring errors!&quot;);<br>        System.out.println(&quot;Current Editor Text: &quot; + editor.getContent());<br><br>        // 4. Hit Undo once (Pops the mistake state, falls back to checkpoint 2)<br>        System.out.println(&quot;\n--- Triggering First Undo ---&quot;);<br>        editor.restore(history.pop()); <br>        <br>        // 5. Hit Undo again (Falls back to checkpoint 1)<br>        System.out.println(&quot;\n--- Triggering Second Undo ---&quot;);<br>        editor.restore(history.pop());<br><br>        System.out.println(&quot;\nFinal Screen Output: &quot; + editor.getContent());<br>    }<br>}</pre><h3>How the We Resolve It: Three Distinct Responsibilities</h3><h4>1. The Originator (TextEditor) — The Creator &amp; Consumer</h4><ul><li><strong>Role:</strong> It holds the active data you are modifying (e.g., text).</li><li><strong>Key Power:</strong> It is the <strong>only component</strong> allowed to create a snapshot (save()) or extract data from a snapshot (restore()).</li><li><strong>Why this matters:</strong> The internal data structure stays completely private to the TextEditor.</li></ul><h4>2. The Memento (EditorMemento) — The Sealed Snapshot</h4><ul><li><strong>Role:</strong> An immutable data box holding the exact state at a given second.</li><li><strong>Key Power:</strong> It acts as a passive container. Once initialized, its variables cannot be altered (final).</li><li><strong>Access Control:</strong> The getter methods are restricted (package-private or protected) so that external code cannot inspect or tamper with the state.</li></ul><h4>3. The Caretaker (HistoryTracker) — The Administrator</h4><ul><li><strong>Role:</strong> A stack or list that holds the order of saved checkpoints over time (LIFO: Last In, First Out).</li><li><strong>Key Constraint:</strong> It handles mementos as <strong>black boxes</strong>. It knows <em>when</em> to store a snapshot (push()) and <em>when</em> to pop one (pop()), but it <strong>never reads or alters</strong> what is inside.</li></ul><h3>Real-World Use Cases of the Memento Pattern</h3><h4>1. Multi-Level Undo/Redo in Software Applications</h4><ul><li><strong>Examples:</strong> Text editors (VS Code, Microsoft Word), graphics tools (Photoshop, Figma), and digital audio workstations (Ableton).</li><li><strong>How it works:</strong> Every time you type a block of text, draw a vector path, or add an audio effect, the application captures a state snapshot. Hitting Ctrl + Z pops the latest snapshot off the history stack and restores the canvas or document to that precise point in time.</li></ul><h4>2. Database &amp; Application Transactions (Rollback Systems)</h4><ul><li><strong>Examples:</strong> Banking operations, e-commerce checkout flows, and ORMs (Object-Relational Mappers).</li><li><strong>How it works:</strong> When performing complex, multi-step operations (e.g., deducting funds from Account A and adding to Account B), the system saves the initial state as a checkpoint. If any step fails halfway through, the system triggers a rollback, using the stored Memento to revert the database state to its original, uncorrupted form.</li></ul><h4>3. Save / Load Checkpoints in Video Games</h4><ul><li><strong>Examples:</strong> Single-player strategy games, RPGs (e.g., <em>Civilization</em>, <em>The Witcher</em>), or retro console emulators (“Save States”).</li><li><strong>How it works:</strong> A save state freezes player stats, inventory items, NPC positions, and map progress into a single binary file (the Memento). Players can load this file anytime to restore the exact game world state without exposing or modifying the underlying game engine logic.</li></ul><h4>4. Browser History &amp; Navigation</h4><ul><li><strong>Examples:</strong> Web browsers (Chrome, Firefox, Safari) and single-page application (SPA) routers (React Router).</li><li><strong>How it works:</strong> As you navigate between pages, the browser stores state information (URL, scroll position, form inputs) in a history stack. Clicking the “Back” button retrieves the previous state snapshot from the caretaker and restores the view without re-initializing the entire application state.</li></ul><h4>5. Drafts &amp; Auto-Save Systems</h4><ul><li><strong>Examples:</strong> Email clients (Gmail), blogging platforms (Medium, WordPress), and form wizards.</li><li><strong>How it works:</strong> While you compose content, an auto-save background job periodically generates snapshots of your draft. If your browser crashes or network drops, the application fetches the latest saved memento to seamlessly restore your unsaved work.</li></ul><p>Use the Memento Pattern whenever you need to implement <strong>time-travel features</strong> (undo, rollback, save-points) where an object’s state must be preserved and restored <strong>without violating encapsulation rules</strong>.</p><p>I hope you guys enjoyed reading this article!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c2c67363f6cc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[LLD Patterns: Visitor Design Pattern]]></title>
            <link>https://medium.com/@gupta_harshal/lld-patterns-visitor-design-pattern-232af52eb4ed?source=rss-43619e04b875------2</link>
            <guid isPermaLink="false">https://medium.com/p/232af52eb4ed</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[design]]></category>
            <dc:creator><![CDATA[Harshal Gupta]]></dc:creator>
            <pubDate>Wed, 17 Jun 2026 19:56:20 GMT</pubDate>
            <atom:updated>2026-06-17T19:56:20.960Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/852/1*z-Ov50wM8uEorlz6LeYvFg.png" /></figure><blockquote>The <strong>Visitor Design Pattern</strong> is a behavioral design pattern that lets you separate algorithms and operations from the objects on which they operate.</blockquote><blockquote>Think of a home or a business. You have a <strong>House</strong> object and a <strong>Factory</strong> object. If the government decides to introduce a new <strong>Property Tax</strong>, you don’t rewrite the internal plumbing of the House or the Factory to calculate taxes.</blockquote><blockquote>Instead, a <strong>Tax Inspector (The Visitor)</strong> walks into the House, inspects the rooms, calculates the tax, and leaves. Tomorrow, if the government wants to calculate <strong>Insurance Risk</strong>, you don’t change the House code either; you just create an <strong>Insurance Agent (A New Visitor)</strong> who walks through the exact same buildings.</blockquote><h4>Code Overview</h4><pre>// 1. The Visitor Interface (Defines operation entry points for each concrete element)<br>interface ReportVisitor {<br>    void visit(TextFile file);<br>    void visit(VideoFile file);<br>}<br><br>// 2. The Element Interface (Enables components to accept any visitor dynamically)<br>interface DocumentElement {<br>    void accept(ReportVisitor visitor);<br>}<br><br>// 3. Concrete Element A: Text File<br>class TextFile implements DocumentElement {<br>    private String fileName;<br>    private int wordCount;<br><br>    public TextFile(String fileName, int wordCount) {<br>        this.fileName = fileName;<br>        this.wordCount = wordCount;<br>    }<br><br>    public String getFileName() { return fileName; }<br>    public int getWordCount() { return wordCount; }<br><br>    @Override<br>    public void accept(ReportVisitor visitor) {<br>        // Double Dispatch: Element hands control over to the visitor, passing itself<br>        visitor.visit(this);<br>    }<br>}<br><br>// 4. Concrete Element B: Video File<br>class VideoFile implements DocumentElement {<br>    private String title;<br>    private int durationInSeconds;<br><br>    public VideoFile(String title, int durationInSeconds) {<br>        this.title = title;<br>        this.durationInSeconds = durationInSeconds;<br>    }<br><br>    public String getTitle() { return title; }<br>    public int getDurationInSeconds() { return durationInSeconds; }<br><br>    @Override<br>    public void accept(ReportVisitor visitor) {<br>        visitor.visit(this);<br>    }<br>}<br><br>// 5. Concrete Visitor 1: Generates a plain text metadata summary<br>class MetadataExtractor implements ReportVisitor {<br>    @Override<br>    public void visit(TextFile file) {<br>        System.out.println(&quot;Text Metadata -&gt; File: &quot; + file.getFileName() + &quot;, Words: &quot; + file.getWordCount());<br>    }<br><br>    @Override<br>    public void visit(VideoFile file) {<br>        System.out.println(&quot;Video Metadata -&gt; Title: &quot; + file.getTitle() + &quot;, Runtime: &quot; + file.getDurationInSeconds() + &quot;s&quot;);<br>    }<br>}<br><br>// 6. Concrete Visitor 2: Calculates disk storage or cloud hosting costs<br>class HostingCostCalculator implements ReportVisitor {<br>    @Override<br>    public void visit(TextFile file) {<br>        // Low cost for text<br>        double cost = file.getWordCount() * 0.001;<br>        System.out.println(&quot;Text Storage Cost estimate for &quot; + file.getFileName() + &quot;: $&quot; + String.format(&quot;%.4f&quot;, cost));<br>    }<br><br>    @Override<br>    public void visit(VideoFile file) {<br>        // High cost for video streaming bandwidth<br>        double cost = file.getDurationInSeconds() * 0.15;<br>        System.out.println(&quot;Video Bandwidth Cost estimate for &quot; + file.getTitle() + &quot;: $&quot; + String.format(&quot;%.2f&quot;, cost));<br>    }<br>}<br><br>// 7. Execution Driver<br>public class Main {<br>    public static void main(String[] args) {<br>        // A diverse collection of object elements<br>        DocumentElement[] library = new DocumentElement[] {<br>            new TextFile(&quot;readme.txt&quot;, 450),<br>            new VideoFile(&quot;tutorial.mp4&quot;, 1200),<br>            new TextFile(&quot;essay.docx&quot;, 2300)<br>        };<br><br>        // Instantiate completely separate business operations (Visitors)<br>        ReportVisitor extractor = new MetadataExtractor();<br>        ReportVisitor costCalculator = new HostingCostCalculator();<br><br>        System.out.println(&quot;--- Operation 1: Extracting Metadata ---&quot;);<br>        for (DocumentElement element : library) {<br>            element.accept(extractor);<br>        }<br><br>        System.out.println(&quot;\n--- Operation 2: Calculating Financial Costs ---&quot;);<br>        for (DocumentElement element : library) {<br>            element.accept(costCalculator);<br>        }<br>    }<br>}</pre><p>.</p><h4>1. The Elements: The Fixed Object Structures</h4><pre>class TextFile implements DocumentElement { ... }<br>class VideoFile implements DocumentElement { ... }</pre><p>In our code, TextFile and VideoFile represent your core data entities. Notice that their internal properties are completely mismatched: a TextFile cares about wordCount, while a VideoFile cares about durationInSeconds.</p><ul><li><strong>The Design Win:</strong> These classes are completely clean. They do not contain any chaotic logic about printing text, calculating money, rendering screens, or parsing analytics. They only store data and expose getters. They are completely locked down.</li></ul><h4>2. The Visitors: The Fluid External Operations</h4><p>Instead of forcing the file classes to handle data operations, you extract those operations into separate, isolated classes that implement ReportVisitor.</p><pre>class MetadataExtractor implements ReportVisitor { ... }<br>class HostingCostCalculator implements ReportVisitor { ... }</pre><p>Each visitor behaves like a specialized tool walking through a factory.</p><ul><li>When the HostingCostCalculator visits, it calculates financial data ($0.001 per word vs $0.15 per second)</li><li>When the MetadataExtractor visits, it handles basic logging and string parsing.</li></ul><p>If you want to add a third operation tomorrow — like CloudBackupExporter or ContentModeratorAI—<strong>you do not edit the file classes.</strong> You simply write a new visitor class. This perfectly satisfies the <strong>Open/Closed Principle</strong>.</p><h4>3. The Double Dispatch Handshake (How it Executes)</h4><p>The hardest part of the Visitor pattern for developers to wrap their heads around is <em>why</em> we need element.accept(visitor) instead of just calling a method directly. This mechanism is called <strong>Double Dispatch</strong>.</p><p>Let’s trace exactly what happens in memory when tutorial.mp4 meets the HostingCostCalculator inside your main loop:</p><pre>Step 1: The Loop Invocation<br>        library[1].accept(costCalculator); <br>        (The runtime only knows library[1] is a generic &#39;DocumentElement&#39;)<br>Step 2: The First Dispatch (Locating the correct Element)<br>        Java looks at the actual object instance, realizes it&#39;s a &#39;VideoFile&#39;, <br>        and jumps directly into VideoFile&#39;s concrete accept() method:<br>        <br>        public void accept(ReportVisitor visitor) {<br>            visitor.visit(this);  &lt;-- &#39;this&#39; is explicitly compiled as a VideoFile type!<br>        }<br>Step 3: The Second Dispatch (Locating the correct Visitor Operation)<br>        The element hands execution right back to the visitor by calling visit(this). <br>        Because &#39;this&#39; is a concrete VideoFile object, Java routes it directly to:<br>        <br>        HostingCostCalculator.visit(VideoFile file) { ... }</pre><h3>Why can’t we just use regular overloading?</h3><p>Java resolves method overloading at <strong>compile time</strong>, but it resolves polymorphism (overriding) at <strong>runtime</strong>.</p><p>If you tried to bypass accept() and just call costCalculator.visit(element), the compiler would throw an error because it doesn&#39;t see a generic visit(DocumentElement) method inside your visitor interface. The accept() method forces the object to reveal its true underlying subclass type to the visitor at runtime.</p><h3>Real World Use Cases</h3><h4>1. Abstract Syntax Trees (ASTs) in Compilers</h4><p>If you look at how languages like Java, TypeScript, or Python are compiled, they use the Visitor pattern as their architectural backbone.</p><ul><li><strong>The Analogy to Your Code:</strong> * Instead of TextFile and VideoFile, the elements are code structures like IfStatementNode, ForLoopNode, or VariableAssignmentNode.</li><li>Instead of MetadataExtractor, the compiler team writes completely independent operations called <strong>Visitor Passes</strong>.</li><li><strong>Real-World Operations:</strong></li><li><strong>Pass 1 (</strong><strong>TypeCheckingVisitor):</strong> Walks through the code tree to ensure you aren&#39;t trying to add a string to an integer.</li><li><strong>Pass 2 (</strong><strong>OptimizationVisitor):</strong> Walks through the exact same tree to find dead code (code that never runs) and deletes it to optimize performance.</li><li><strong>Pass 3 (</strong><strong>BytecodeGeneratorVisitor):</strong> Walks through the tree one last time to convert the code into the final executable machine binary.</li></ul><h4>2. E-Commerce Checkout &amp; Tax Compliance Matrix</h4><p>Large global e-commerce platforms cannot put tax, shipping, or discount algorithms directly inside their product inventory classes because fiscal laws change constantly.</p><ul><li><strong>The Analogy to Your Code:</strong> * The elements are the items in a shopping cart: ElectronicsItem, FreshFoodItem, MedicalSupplyItem.</li><li>The visitors are the operational checkouts.</li><li><strong>Real-World Operations:</strong></li><li><strong>USStateTaxVisitor:</strong> Walks through the cart. It knows that electronics have a 7% tax, fresh food has a 0% tax, and medical supplies are exempt.</li><li><strong>CustomsDutyVisitor:</strong> If the package is shipping internationally, this visitor runs through the same items to apply border customs fees.</li><li><strong>The Win:</strong> If the government changes the food tax rate tomorrow, you only rewrite <em>one single file</em> (the food tax visitor). You don’t risk touching or breaking the core checkout inventory system.</li></ul><h4>3. Cloud Security &amp; Asset Compliance Auditing</h4><p>In cloud infrastructures like AWS or Azure, security tools constantly scan enterprise setups to ensure data is secure.</p><ul><li><strong>The Analogy to Your Code:</strong> * The elements are cloud resources: S3BucketElement, EC2ServerElement, RDSDatabaseElement.</li><li>The visitors are security rules.</li><li><strong>Real-World Operations:</strong></li><li><strong>PublicExposureAuditor (Visitor 1):</strong> Scans each element to check if it&#39;s accidentally open to the public internet. It reads S3BucketElement.isPublic() and flags an alert if true.</li><li><strong>CostOptimizationAuditor (Visitor 2):</strong> Scans the exact same elements to check for underutilization. If an EC2ServerElement has been sitting idle at 1% CPU capacity for a week, it flags it for downsizing to save money.</li></ul><h4>4. Financial Portfolio Reporting Engines</h4><p>Wealth management applications handle complex asset portfolios that hold a mix of different financial products.</p><ul><li><strong>The Analogy to the Code:</strong></li><li>The elements are financial instruments: EquityStock, GovernmentBond, CryptoAsset.</li><li>The visitors are analytics engines.</li><li><strong>Real-World Operations:</strong></li><li><strong>CurrentValueExtractor:</strong> Feeds on live HTTP market feeds to calculate the exact net worth of the portfolio.</li><li><strong>RiskAssessmentVisitor:</strong> Evaluates volatility. It handles CryptoAsset with a high-risk multiplier and GovernmentBond with a low-risk stability calculation to output a blended risk-score matrix for the investor.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=232af52eb4ed" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[LLD Patterns: Chain of Responsibility Design Pattern]]></title>
            <link>https://medium.com/@gupta_harshal/lld-patterns-chain-of-responsibility-design-pattern-050a47e03fea?source=rss-43619e04b875------2</link>
            <guid isPermaLink="false">https://medium.com/p/050a47e03fea</guid>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Harshal Gupta]]></dc:creator>
            <pubDate>Wed, 17 Jun 2026 15:06:26 GMT</pubDate>
            <atom:updated>2026-06-17T15:06:26.971Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>This pattern is designed to decouple the sender of a request from its potential receivers. Instead of one specific function handling a request, you create a <strong>chain of potential handlers</strong>. The request “travels” down this chain until one handler recognizes it and takes action.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/853/1*le2fgos-Hw5Xfzep4ZITQg.png" /></figure><p>Instead of a single entity trying to know everything, think of the Chain of Responsibility as an automated conveyor belt in a logistics warehouse.</p><ul><li>A package (The SupportTicket payload) is placed on the belt.</li><li>The package moves past different specialized robotic arms (The SupportHandlers).</li><li>Each arm looks at the label on the box. If the label matches its exact specialty, that arm grabs the box, processes it, and takes it off the belt. If the label doesn’t match, the arm does absolutely nothing — it simply allows the conveyor belt to carry the box forward to the next specialized station.</li></ul><h3>Code Sample</h3><pre>// 1. The Request Object<br>class SupportTicket {<br>    private String description;<br>    private int severityLevel; // 1: Low, 2: Medium, 3: High<br><br>    public SupportTicket(String description, int severityLevel) {<br>        this.description = description;<br>        this.severityLevel = severityLevel;<br>    }<br><br>    public String getDescription() { return description; }<br>    public int getSeverityLevel() { return severityLevel; }<br>}<br><br>// 2. The Handler Interface (Abstract Class to enforce chaining logic)<br>abstract class SupportHandler {<br>    protected SupportHandler nextHandler;<br><br>    // Sets the next element in the pipeline<br>    public void setNextHandler(SupportHandler nextHandler) {<br>        this.nextHandler = nextHandler;<br>    }<br><br>    // Template-style method to handle execution delegation<br>    public final void handleRequest(SupportTicket ticket) {<br>        if (canHandle(ticket)) {<br>            process(ticket);<br>        } else if (nextHandler != null) {<br>            System.out.println(getClass().getSimpleName() + &quot; cannot handle. Escalating...&quot;);<br>            nextHandler.handleRequest(ticket);<br>        } else {<br>            System.out.println(&quot;Ticket [&quot; + ticket.getDescription() + &quot;] could not be resolved by any department.&quot;);<br>        }<br>    }<br><br>    protected abstract boolean canHandle(SupportTicket ticket);<br>    protected abstract void process(SupportTicket ticket);<br>}<br><br>// 3. Concrete Handler 1: Front Desk Bot<br>class AutomatedBotHandler extends SupportHandler {<br>    @Override<br>    protected boolean canHandle(SupportTicket ticket) {<br>        return ticket.getSeverityLevel() == 1;<br>    }<br><br>    @Override<br>    protected void process(SupportTicket ticket) {<br>        System.out.println(&quot;AutomatedBot: Resolved ticket -&gt; &quot; + ticket.getDescription());<br>    }<br>}<br><br>// 4. Concrete Handler 2: Level 1 Agent<br>class Level1AgentHandler extends SupportHandler {<br>    @Override<br>    protected boolean canHandle(SupportTicket ticket) {<br>        return ticket.getSeverityLevel() == 2;<br>    }<br><br>    @Override<br>    protected void process(SupportTicket ticket) {<br>        System.out.println(&quot;Level1Agent: Resolved ticket -&gt; &quot; + ticket.getDescription());<br>    }<br>}<br><br>// 5. Concrete Handler 3: Tech Lead<br>class TechLeadHandler extends SupportHandler {<br>    @Override<br>    protected boolean canHandle(SupportTicket ticket) {<br>        return ticket.getSeverityLevel() == 3;<br>    }<br><br>    @Override<br>    protected void process(SupportTicket ticket) {<br>        System.out.println(&quot;TechLead: Resolved critical ticket -&gt; &quot; + ticket.getDescription());<br>    }<br>}<br><br>// 6. Execution Driver<br>public class Main {<br>    public static void main(String[] args) {<br>        // Create individual chain segments<br>        SupportHandler bot = new AutomatedBotHandler();<br>        SupportHandler agent = new Level1AgentHandler();<br>        SupportHandler techLead = new TechLeadHandler();<br><br>        // Configure the linking order: Bot -&gt; Agent -&gt; Tech Lead<br>        bot.setNextHandler(agent);<br>        agent.setNextHandler(techLead);<br><br>        // Injecting distinct tickets into the head of the chain<br>        SupportTicket t1 = new SupportTicket(&quot;Check account balance&quot;, 1);<br>        SupportTicket t2 = new SupportTicket(&quot;Router configurations mismatch&quot;, 2);<br>        SupportTicket t3 = new SupportTicket(&quot;Database cluster server downtime&quot;, 3);<br><br>        System.out.println(&quot;--- Ticket 1 Entering Chain ---&quot;);<br>        bot.handleRequest(t1);<br><br>        System.out.println(&quot;\n--- Ticket 2 Entering Chain ---&quot;);<br>        bot.handleRequest(t2);<br><br>        System.out.println(&quot;\n--- Ticket 3 Entering Chain ---&quot;);<br>        bot.handleRequest(t3);<br>    }<br>}</pre><p>To see how this operates at scale, let’s look at how the execution logic actually separates the <strong>Routing Control</strong> from the <strong>Business Logic</strong>.</p><h4>1. The Core Infrastructure (The Base Handler)</h4><p>Your abstract class acts as the framework engine. It completely isolates the concrete handlers so they never have to worry about how the next step in the sequence is called.</p><pre>public abstract class SupportHandler {<br>    protected SupportHandler nextHandler;<br>    public void setNextHandler(SupportHandler nextHandler) {<br>        this.nextHandler = nextHandler;<br>    }<br>    // The Template Method: Controls the flow of data<br>    public final void handleRequest(SupportTicket ticket) {<br>        if (canHandle(ticket)) {<br>            process(ticket); // Route inside the concrete class<br>        } else if (nextHandler != null) {<br>            nextHandler.handleRequest(ticket); // Forward down the line<br>        } else {<br>            System.out.println(&quot;End of chain reached. Ticket unresolved.&quot;);<br>        }<br>    }<br>    protected abstract boolean canHandle(SupportTicket ticket);<br>    protected abstract void process(SupportTicket ticket);<br>}</pre><h4>2. The Isolated Workers (Concrete Handlers)</h4><p>Because the base class handles all the complex traversal math, your individual business logic classes remain incredibly lean, clean, and highly readable. They only focus on doing one specific job perfectly.</p><pre>class Level1AgentHandler extends SupportHandler {<br>    @Override<br>    protected boolean canHandle(SupportTicket ticket) {<br>        return ticket.getSeverityLevel() == 2; // Simple condition check<br>    }<br>    @Override<br>    protected void process(SupportTicket ticket) {<br>        System.out.println(&quot;Level 1 Agent processing: &quot; + ticket.getDescription());<br>    }<br>}</pre><p>Implementing your system this way unlocks three major software design advantages:</p><ul><li><strong>The Open/Closed Principle (SOLID):</strong> If your engineering team decides to add a new “Senior Escalations Manager” tier tomorrow to handle a new classification of tickets, you do not have to touch a single line of code inside AutomatedBotHandler or Level1AgentHandler. You simply create a brand-new class and link it to the end of the chain.</li><li><strong>Single Responsibility Principle:</strong> Each processing block is completely isolated. Your bot doesn’t know how the agent works, and the agent doesn’t know how the tech lead works. This makes debugging incredibly simple because you know exactly which file to open if a specific layer fails.</li><li><strong>Dynamic Reconfiguration:</strong> Because the links are joined together at runtime using setNextHandler(), you can change the behavior of your system dynamically based on external conditions. For example, if the Level1Agent logs off for the weekend, your system initialization code can dynamically re-route the chain to bypass the agent entirely and send tickets straight from the AutomatedBot to the TechLead.</li></ul><h3>Real World Use Cases</h3><h4>1. HTTP Request Middleware &amp; Security Filters</h4><p>This is the single most common use case in modern web development (found natively in frameworks like <strong>Spring Security, Express.js, and ASP.NET Core</strong>).</p><ul><li><strong>The Scenario:</strong> Before an API request reaches your database or business logic, it must pass a battery of checks: logging, rate-limiting, authentication, and blacklisting.</li><li><strong>How the Chain Handles It:</strong> * RateLimitHandler: Checks if an IP has sent too many requests. If yes, it <strong>short-circuits</strong> the chain (returns a 429 Too Many Requests error). If no, it passes to the next link.</li><li>AuthenticationHandler: Decodes the user&#39;s JWT token. If valid, it forwards the request; if invalid, it drops the chain.</li><li>CORSFilter: Validates the domain origin before finally handing the request to the application router.</li></ul><h4>2. E-Commerce Order Validation Pipeline</h4><p>Large online platforms cannot run checkout operations as a single, massive monolithic function. They break it up into an processing assembly line.</p><ul><li><strong>The Scenario:</strong> When a customer clicks “Place Order,” the system must perform multiple disjointed business validations before charging the customer’s credit card.</li><li><strong>How the Chain Handles It:</strong>InventoryCheckHandler: Verifies if items are physically still in stock.</li><li>FraudDetectionHandler: Runs a risk algorithm to verify if the transaction pattern looks stolen or malicious.</li><li>TaxCalculationHandler: Dynamically calculates regional state and country taxes based on the shipping address.</li><li>PaymentGatewayHandler: Finally executes the bank payment capture.</li><li><strong>The Structural Win:</strong> If a coupon system fails or tax laws change, you only rewrite or toggle that <em>one specific link</em> in the pipeline without risking the stability of the payment engine.</li></ul><h4>3. Enterprise Logging Frameworks (Log4j / Logback)</h4><p>If you look at how Java handles log routing under the hood, it relies heavily on a hierarchical Chain of Responsibility.</p><ul><li><strong>The Scenario:</strong> A system outputs different levels of logs (DEBUG, INFO, WARN, ERROR), and they need to be routed to different destinations depending on severity.</li><li><strong>How the Chain Handles It:</strong>ConsoleLogger: Captures <em>everything</em> (DEBUG and above) and prints it to the local developer terminal. Passes the log down.</li><li>FileLogger: Filters for WARN or ERROR messages and appends them to a persistent server log file. Passes the log down.</li><li>PagerDutyLogger: Watches <em>only</em> for catastrophic FATAL/CRITICAL server failures. If triggered, it fires an immediate SMS/api alert to the on-call DevOps engineer&#39;s phone.</li></ul><h4>4. UI Event Bubbling (Web &amp; Mobile OS Architecture)</h4><p>Every time you click a button on a web page or tap an element on an Android/iOS screen, the OS uses this pattern to decide who responds to that gesture.</p><ul><li><strong>The Scenario:</strong> You tap an HTML &lt;button&gt; inside a &lt;div&gt; box, which sits inside a &lt;body&gt; tag.</li><li><strong>How the Chain Handles It: </strong>The system asks the innermost element: <em>“Button, do you have an </em><em>onClick listener bound to you?&quot;</em> If yes, it executes the code and stops.</li><li>If the button doesn’t care, the click event <strong>bubbles up</strong> to the parent &lt;div&gt;.</li><li>If the &lt;div&gt; doesn&#39;t handle it, it escalates to the &lt;body&gt;, and eventually up to the window object itself until a component consumes the click event.</li></ul><h4>5. Multi-Stage Document Approval Workflows</h4><p>Enterprise HR, FinTech, and banking ERP applications heavily utilize this pattern to manage corporate permissions.</p><ul><li><strong>The Scenario:</strong> An employee submits an expense reimbursement request.</li><li><strong>How the Chain Handles It: </strong>TeamLeadHandler: Can approve amounts up to ₹10,000. If the ticket is for ₹50,000, they cannot handle it; the request automatically escalates down the chain.</li><li>DepartmentHeadHandler: Can approve amounts up to ₹1,00,000.</li><li>CFOHandler: The ultimate fallback node that handles any amount above that threshold.</li><li><strong>The Structural Win:</strong> The employee application only calls .submitRequest(expense). The system takes care of finding the exact manager dynamically based on the financial payload scale.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=050a47e03fea" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>