Kubernate

Design Pattern # Proxy Pattern

 Here is a clear, real-world example of the Proxy Design Pattern with pictures + Java example — perfect for interviews.


Proxy Design Pattern (Real-World Example: ATM Machine)




The ATM acts as a Proxy to the Bank Server.

You never connect directly to the bank’s core system —
the ATM verifies your PIN, checks balance, logs your request, and then forwards only required operations to the bank server.

Image

Image

Image


🎯 Why ATM is a Perfect Real-World Proxy Example?

Component Role in Proxy Pattern
ATM Machine Proxy — controls access to bank server
Bank Server Real Object — executes actual operations (withdraw, balance inquiry)
User Client

ATM handles:

  • Security (PIN validation)

  • Logging

  • Connection handling
    Before calling the actual bank server.


JAVA IMPLEMENTATION — ATM as Proxy

1️⃣ Subject Interface

interface Bank {
    void withdraw(String accountNo, double amount);
}

2️⃣ Real Object (Actual Bank Server)

class BankServer implements Bank {
    @Override
    public void withdraw(String accountNo, double amount) {
        System.out.println("Amount " + amount + " withdrawn from: " + accountNo);
    }
}

3️⃣ Proxy Class (ATM Machine)

class ATMProxy implements Bank {

    private BankServer bankServer;

    public ATMProxy() {
        bankServer = new BankServer();
    }

    private boolean validateUser(String accountNo) {
        System.out.println("Validating user for account: " + accountNo);
        return true;
    }

    @Override
    public void withdraw(String accountNo, double amount) {
        if (validateUser(accountNo)) {
            System.out.println("User validated. Processing...");
            bankServer.withdraw(accountNo, amount);  // Real object call
        }
    }
}

4️⃣ Client Code

public class Client {
    public static void main(String[] args) {
        Bank atm = new ATMProxy();
        atm.withdraw("ACC12345", 5000);
    }
}

πŸ“Œ Another Real-World Example (with picture): Firewall Proxy

A network firewall acts as a Proxy between a user and the internet — it controls who can access what.

Image

Image

Image

Firewall (Proxy)
✔ Filters traffic
✔ Blocks unauthorized access
✔ Logs requests

Actual Server (Real Object)
✔ Only receives safe, filtered requests


πŸ“ Interview-Ready Summary

Proxy Pattern = A substitute or placeholder to control access to the real object.

Real-World Examples:

  • ATM → Proxy for Bank Server

  • Firewall → Proxy for internal servers

  • NGINX → Reverse proxy for backend services

  • Virtual Proxy → Lazy loading images in UI

  • Protection Proxy → Role-based access



No comments:

Post a Comment

Spring Boot - Bean LifeCycle

 Here is a clear, step-by-step lifecycle of a Spring Boot application , explained in a simple + interview-ready way. πŸ”„ Spring Boot Applica...

Kubernate