Skip to main content

Command Palette

Search for a command to run...

Proxy Design Pattern

Published
•2 min read•View as Markdown
P

Hi , thanks for stopping by!

I am full-stack developer and I'm passionate about making complex concepts clear through code and visuals. After all, a picture (and a code snippet) is worth a thousand words!

I hope you enjoy my blog.

To understand pattern, we will first understand the below current flow first .

Current flow


/**
 * LegacyBank (Client)
 */
public class LegacyBank {

    private String data = "payment data";

    public void process(Payment payment) {
        System.out.println("LegacyBank make the payment ");
        payment.makePayment(this.data);
    }
}

/**
 * Payment(Subject).
 */
interface Payment {
    public void makePayment(String data) ;
}

/**
 * PaymentService -(RealSubject).
 */
public class PaymentService implements Payment {
    public void makePayment(String data) {
        System.out.println("Successfully processed payment data ");
    }
}
public class PatternTest {

    public static void main(String[] args) throws Exception {
        LegacyBank bank = new LegacyBank();
        bank.process(new PaymentService());
    }
}

//output
LegacyBank make the payment 
Successfully processed payment data

Now I want to add some extra functionality before and after the Payment without changing the Subject(Payment) and client(LegacyBank ) code and RealSubject(PaymentService).

We are going to use Proxy Pattern to achieve this .

Proxy Flow


/**
 * PaymentGateway (ProxySubject)
 */
public class PaymentGateway implements Payment {

    private PaymentService paymentService = new PaymentService();

    public void makePayment(String data) {
        additionCheck();
        paymentService.makePayment(data);
        additionLogs();
    }

    private void additionCheck() {
        System.out.println("Check the user is authenticated");
    }

    private void additionLogs() {
        System.out.println("Capturing the payment detail");
    }
}

public class PatternTest {

    public static void main(String[] args) throws Exception {
        LegacyBank bank = new LegacyBank();        
        bank.process(new PaymentGateway());
    }
}

//output

LegacyBank make the payment 
Check the user is authenticated
Successfully processed payment data 
Capturing the payment detail