The Wayback Machine - https://web.archive.org/web/20240927012910/https://www.geeksforgeeks.org/proxy-method-design-pattern-in-java/
Open In App

Proxy Method Design Pattern in Java

Last Updated : 11 Jan, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

A Proxy Method or Proxy Design Pattern is a structural design pattern that provides a surrogate or placeholder for another object to control access to it. This pattern involves creating a new class, known as the proxy, which acts as an intermediary between a client and the real object. The proxy object controls access to the real object, allowing you to add additional functionality, such as lazy loading, access control, logging, or caching, without changing the actual object’s code.

Proxy-method-Design-Pattern-in-Java

Example of Proxy Method Design Pattern in Java

Problem Statement:

We have to create a simple banking application with a proxy to control access to the real bank account.

Key Concepts of Proxy Method Design Pattern in Java

  • Subject Interface (or Abstract Class): This is the common interface or abstract class that both the RealSubject (the real object) and the Proxy implement. It defines the operations that the Proxy will control access to.
  • RealSubject: This is the real object that the Proxy represents. It implements the Subject interface. It provides the actual implementation of the operations declared in the Subject interface.
  • Proxy: The Proxy class implements the Subject interface as well. It holds a reference to the RealSubject and controls access to it. The Proxy may provide additional functionality before or after assigning the operation to the RealSubject.
  • Client: The client code interacts with the Proxy as if it were the real object. The client is unaware of whether it’s using the real object or a proxy.

Step wise Step Implementation of above Proxy Method Design Pattern in Java:

“BankAccount” (Subject Interface): This is the subject interface that both the real and proxy objects will implement. It declares three methods: “deposit”, “withdraw,” and “getBalance”.

Java




// Subject interface
interface BankAccount {
    void deposit(double amount);
    void withdraw(double amount);
    double getBalance();
}


“RealBankAccount” (RealSubject) Class: “RealBankAccount” is the real subject class implementing the “BankAccount” interface. It maintains a balance and provides implementations for the deposit, withdraw, and getBalance methods.

Java




// RealSubject class
class RealBankAccount implements BankAccount {
    private double balance;
 
    @Override
    public void deposit(double amount) {
        balance += amount;
        System.out.println("Deposited: " + amount);
    }
 
    @Override
    public void withdraw(double amount) {
        if (balance >= amount) {
            balance -= amount;
            System.out.println("Withdrawn: " + amount);
        } else {
            System.out.println("Insufficient funds!");
        }
    }
 
    @Override
    public double getBalance() {
        return balance;
    }
}


“SecureBankAccountProxy” (Proxy) Class: “SecureBankAccountProxy” is the proxy class implementing the BankAccount interface. It contains a reference to the real bank account (“RealBankAccount”) and requires a password for authentication during instantiation. The “authenticate” method checks the password and initializes the real bank account if authentication is successful. The “deposit”, “withdraw”, and “getBalance” methods delegate to the corresponding methods of the real bank account.

Java




// Proxy class
class SecureBankAccountProxy implements BankAccount {
    private RealBankAccount realBankAccount;
    private String password;
 
    public SecureBankAccountProxy(String password) {
        this.password = password;
        authenticate();
    }
 
    private void authenticate() {
        if (password.equals("secret")) {
            realBankAccount = new RealBankAccount();
            System.out.println("Authentication successful.");
        } else {
            System.out.println("Authentication failed. Access denied.");
        }
    }
 
    @Override
    public void deposit(double amount) {
        if (realBankAccount != null) {
            realBankAccount.deposit(amount);
        }
    }
 
    @Override
    public void withdraw(double amount) {
        if (realBankAccount != null) {
            realBankAccount.withdraw(amount);
        }
    }
 
    @Override
    public double getBalance() {
        return (realBankAccount != null) ? realBankAccount.getBalance() : 0.0;
    }
}


“ProxyBankExample” Class (Client): “ProxyBankExample” is the client code that demonstrates the usage of the proxy. It creates an instance of “SecureBankAccountProxy” and performs deposit, withdrawal, and balance retrieval operations.

Java




// Client code
public class ProxyBankExample {
    public static void main(String[] args) {
        // Using the proxy to access the real bank account
        BankAccount account = new SecureBankAccountProxy("secret");
 
        // Operations
        account.deposit(1000);
        account.withdraw(500);
        double balance = account.getBalance();
 
        System.out.println("Current Balance: " + balance);
    }
}


Below is the complete combined code of the above example:

To run this code correctly, copy this code and save it in a file named “ProxyBankExample.java”.

Java




// Subject interface
interface BankAccount {
    void deposit(double amount);
    void withdraw(double amount);
    double getBalance();
}
 
// RealSubject class
class RealBankAccount implements BankAccount {
    private double balance;
 
    @Override
    public void deposit(double amount) {
        balance += amount;
        System.out.println("Deposited: " + amount);
    }
 
    @Override
    public void withdraw(double amount) {
        if (balance >= amount) {
            balance -= amount;
            System.out.println("Withdrawn: " + amount);
        } else {
            System.out.println("Insufficient funds!");
        }
    }
 
    @Override
    public double getBalance() {
        return balance;
    }
}
 
// Proxy class
class SecureBankAccountProxy implements BankAccount {
    private RealBankAccount realBankAccount;
    private String password;
 
    public SecureBankAccountProxy(String password) {
        this.password = password;
        authenticate();
    }
 
    private void authenticate() {
        if (password.equals("secret")) {
            realBankAccount = new RealBankAccount();
            System.out.println("Authentication successful.");
        } else {
            System.out.println("Authentication failed. Access denied.");
        }
    }
 
    @Override
    public void deposit(double amount) {
        if (realBankAccount != null) {
            realBankAccount.deposit(amount);
        }
    }
 
    @Override
    public void withdraw(double amount) {
        if (realBankAccount != null) {
            realBankAccount.withdraw(amount);
        }
    }
 
    @Override
    public double getBalance() {
        return (realBankAccount != null) ? realBankAccount.getBalance() : 0.0;
    }
}
 
// Client code
public class ProxyBankExample {
    public static void main(String[] args) {
        // Using the proxy to access the real bank account
        BankAccount account = new SecureBankAccountProxy("secret");
 
        // Operations
        account.deposit(1000);
        account.withdraw(500);
        double balance = account.getBalance();
 
        System.out.println("Current Balance: " + balance);
    }
}


Output

Authentication successful.
Deposited: 1000.0
Withdrawn: 500.0
Current Balance: 500.0


Diagrammatical Representation of the Proxy Method Design Pattern in Java

Diagrammatic-Representation-of-Proxy-Method-Design-Pattern

In this representation:

  • “BankAccount” is the subject interface with “deposit”, “withdraw”, and “getBalance” methods.
  • “RealBankAccount” is the real subject implementing “BankAccount”.
  • “SecureBankAccountProxy” is the proxy implementing “BankAccount”. It contains a reference to a “RealBankAccount” object.
  • “ProxyBankExample” is the client code creating an instance of “SecureBankAccountProxy” and performing operations on it.

The arrows represent the relationships between the classes:

  • The “SecureBankAccountProxy” class contains a reference to a “RealBankAccount” object.
  • The client code “ProxyBankExample” interacts with the “SecureBankAccountProxy”, which may assign operations to the “RealBankAccount”.

Use Cases of Proxy Method Design Pattern in Java

  • Lazy Loading: You can use a proxy to implement lazy loading, where the real object is created and initialized only when it is accessed for the first time. This is beneficial when creating the real object is resource-intensive or time-consuming.
  • Logging: Proxy can be employed for logging method calls, providing a way to log information such as the method name, parameters, and results. This can be helpful for debugging or auditing purposes.
  • Caching: You can use a proxy to implement caching mechanisms. The proxy can check whether the result of a method call is already cached and return the cached result instead of invoking the real object.
  • Virtual Proxy: A virtual proxy can be used to represent expensive objects, such as large images or complex calculations, without loading them into memory until they are actually needed.
  • Protection Proxy: This type of proxy controls access to sensitive operations. For instance, you might use a protection proxy to check if the client has the necessary permissions before allowing a specific operation.
  • Remote Proxy: A remote proxy can be employed when dealing with distributed systems. It acts as a local representative for an object that resides in a different address space, providing a way to interact with it remotely.
  • Monitoring and Metrics: Gather metrics or monitoring data by intercepting method calls. This can be used to collect information about the usage patterns of specific functionalities.

Advantages of the Proxy Method Design Pattern in Java

  • Improved Performance: Proxies improves the performance by controlling the loading and initialization of objects, especially in scenarios where certain operations are resource-intensive.
  • Separation of Concerns: The Proxy Design Pattern promotes a separation of concerns by isolating the proxy-specific functionality from the real object’s implementation. This enhances code modularity and maintainability.
  • Easy Testing: Proxies can be used to create mock objects for testing purposes. This facilitates unit testing by isolating the unit under test from its dependencies, making it easier to control and verify behavior.
  • Dynamic Behavior: Proxies can dynamically alter the behavior of the real object without changing its code. This allows additional functionalities, such as logging or monitoring, without modifying the original implementation.
  • Reduced Resource Usage: Virtual proxies restricts the creation of expensive objects until they are needed. This reduces resource consumption and optimizes memory usage.
  • Enhanced Security: Proxy objects can add an additional layer of security by implementing authentication, authorization, or other security-related checks before allowing access to the real object.

Disadvantages of the Proxy Method Design Pattern in Java

  • Complexity: Introducing proxies can make the codebase complex, especially if multiple types of proxies are involved.
  • Overhead: Proxies may result in extra overhead, especially if there is significant logic in the proxy class, such as logging, monitoring, or security checks. This overhead might impact the overall performance of the system.
  • Increased Development Time: Introducing proxies might require additional development time and effort. Developers need to carefully design and implement the proxy logic, and this can be time-consuming.
  • Misuse or Overuse: There is a risk of misusing or overusing the Proxy Design Pattern. If proxies are applied unnecessarily, it might lead to unnecessary complexity and decreased code readability.
  • Potential Security Risks: Security-related proxies might introduce new risks if not implemented correctly. For example, a security proxy might unintentionally allow unauthorized access.
  • Maintenance Challenges: If not designed and documented properly, the maintenance of proxies and their interactions with real objects can become difficult. Changes to one part of the system may require updating multiple proxy classes.
  • Difficulty in Debugging: The presence of proxy layers can make debugging more challenging, because to find and fix problems, developers must navigate both proxy and real object behaviour.

Conclusion

The Proxy Method Design Pattern in Java is a valuable tool for enhancing control, security, and performance in software systems. When applied correctly and carefully, this pattern provides a modular and flexible approach to extending or modifying the behavior of objects. The pattern provides an effective mechanism for controlling access, optimizing performance, and adding functionalities without directly altering the original object.



Similar Reads

Difference between Forward Proxy and Reverse Proxy
What is Forward Proxy A forward proxy, also referred to as a "proxy server," or simply a "proxy," is a server that sits in front of one or more client computers and serves as a conduit between the clients and the internet. The forward proxy receives the request before sending it on from the client machine to the internet resource. On behalf of the
2 min read
Proxy Method Design Pattern in Javascript
The Proxy Method Design Pattern in JavaScript involves creating a proxy object that controls access to another object, allowing you to define custom behavior for operations like property access and method calls. This pattern is useful for adding features such as logging, validation, and access control in a modular way. In this article, we'll explor
8 min read
Proxy Pattern | C++ Design Patterns
Design Patterns are an essential part of software engineering, offering proven solutions to common problems encountered during software development. One such pattern is the Proxy Pattern. The Proxy Pattern is a structural design pattern that provides a surrogate or placeholder for another object, allowing you to control access to it. This pattern c
7 min read
Proxy Design Pattern
The Proxy Design Pattern is a structural design pattern that provides a surrogate or placeholder for another object to control access to it. This pattern is useful when you want to add an extra layer of control over access to an object. The proxy acts as an intermediary, controlling access to the real object. A real-world example can be a cheque or
8 min read
Behavioral Design Pattern | JavaScript Design Pattern
Behavioral design patterns are a subset of design patterns in software engineering that deal with the interaction and responsibilities of objects. These patterns focus on how objects communicate and work together to achieve common tasks. Important Topics for the Behavioral Design Pattern in JavaScript Design Patterns Uses Cases of the Behavioral De
8 min read
Difference between Prototype Design Pattern and Flyweight Design Pattern
The major point in Prototype vs. Flyweight Design Pattern is that Prototype Design Pattern is a creational design pattern whereas Flyweight Design Pattern is a structural design pattern. In this post, we will look into this and more differences between the Prototype and Flyweight Design Patterns. Let us begin with a basic understanding of each of t
2 min read
Facade Design Pattern | JavaScript Design Pattern
Facade design pattern is a Structural design pattern that allows users to create a simple interface that hides the complex implementation details of the system making it easier to use. This pattern intends to create a simplified and unified interface for a set of interfaces hiding the implementation details making it less complex to use. Important
4 min read
Flyweight Design Pattern - JavaScript Design Pattern
The Flyweight Design Pattern is a structural design pattern used in JavaScript to minimize memory usage by sharing the data as much as possible with the related objects. Important Topics for Flyweight Design PatternDiagramatic Representation:Advantages of Flyweight design pattern:Disadvantages of Flyweight design pattern:The shared data typically c
4 min read
Mediator Design Pattern in JavaScript | Design Pattern
The Mediator pattern is a behavioral design pattern that promotes loose coupling between objects by centralizing communication between them. It's particularly useful when you have a complex system with multiple objects that need to interact and you want to avoid the tight coupling that can arise from direct object-to-object communication. Important
5 min read
Difference Between Builder Design Pattern and Factory Design Pattern
Design patterns provide proven solutions to common problems in software design. The Builder and Factory patterns are two popular creational design patterns. The Builder pattern constructs complex objects step by step. In contrast, the Factory pattern creates objects without specifying their exact class. Both patterns streamline object creation but
7 min read
Proxy Method - Python Design Patterns
The Proxy method is Structural design pattern that allows you to provide the replacement for an another object. Here, we use different classes to represent the functionalities of another class. The most important part is that here we create an object having original object functionality to provide to the outer world. The meaning of word Proxy is "i
4 min read
How Proxy Server Protect Computer Network in System design
In system design, a Proxy Server can be used to protect a computer network in several ways: 1. Filtering and BlockingProxy servers can filter incoming and outgoing traffic based on predefined rules. This can block malicious websites, prevent access to inappropriate content, and filter out harmful files or attachments. 2. Anonymity and PrivacyProxy
2 min read
Difference Between the Facade, Proxy, Adapter, and Decorator Design Patterns
Understanding design patterns is crucial for software developers. Facade, Proxy, Adapter, and Decorator are key patterns that address different aspects of software design, from simplifying interfaces to enhancing functionality. This article explores their distinctions and practical applications in software development. Important Topics for Facade v
4 min read
Strategy Method Design Pattern | C++ Design Patterns
Strategy Pattern is a behavioral design pattern that defines a family of interchangeable algorithms and allows them to be used interchangeably within a context. This pattern enables the algorithm to be selected at runtime, providing flexibility and promoting code reusability. Important Topics for the Strategy Method in C++ Design Patterns Example o
4 min read
State Method Design Pattern | C++ Design Patterns
In software design, managing the behavior of an object according to its internal state is a common issue. The state pattern addresses this issue by allowing an object to alter its behavior every time its internal state changes. This pattern encapsulates each state in a separate class, which makes it easier to add new states and modify existing stat
7 min read
Template Method Design Pattern | C++ Design Patterns
Template Method Pattern introduces a template in a superclass that defines the steps of an algorithm. These steps may include both common tasks shared among subclasses and specific tasks that need customization. Subclasses then implement or override these steps to modify the algorithm according to their specific needs. Important Topics for Template
7 min read
Why is Singleton Design Pattern is Considered an Anti-pattern?
Let us explore why the Singleton pattern, a popular way to ensure only one instance of a class exists, is now seen as problematic in software development. In this article, we will discuss drawbacks such as tight coupling between components, difficulty in unit testing, and issues with scalability in larger applications. Important Topics for Singleto
8 min read
Composite Design Pattern | JavaScript Design Patterns
The Composite Design pattern is a way of organizing objects. It helps us handle different objects in a similar way when they are put together to create a structure with parts and wholes. These parts and wholes are like building blocks that can be split into smaller pieces and then put together to make a tree-like structure. The composite design pat
6 min read
Memento Design Pattern | C++ Design Patterns
Memento Design Pattern is a behavioral design pattern that provides a mechanism for capturing an object's internal state and restoring it to that state at a later time. This pattern is useful when we need to implement features like undo/redo functionality or when we want to save and restore an object's state for various reasons. Important Topics fo
7 min read
Design Patterns Cheat Sheet - When to Use Which Design Pattern?
In system design, selecting the right design pattern is related to choosing the right tool for the job. It's essential for crafting scalable, maintainable, and efficient systems. Yet, among a lot of options, the decision can be difficult. This Design Patterns Cheat Sheet serves as a guide, helping you on the path toward optimal design pattern selec
7 min read
Builder, Fluent Builder, and Faceted Builder Method Design Pattern in Java
Builder Pattern is defined as a creational design pattern that is used to construct a complex object step by step. It separates the construction of an object from its representation, allowing us to create different variations of an object with the same construction code. This pattern is particularly useful when dealing with a complex object with ma
8 min read
Template Method Design Pattern in Java
Template Design Pattern or Template Method is the behavioral design pattern that defines the skeleton of an algorithm in the superclass but lets subclasses override specific steps of the algorithm without changing its structure. This pattern falls under the category of the "behavioral" design patterns as it is concerned with how classes collaborate
10 min read
Strategy Method Design Pattern in Java
Strategy method or Strategy Design Pattern is a behavioral design pattern in Java that defines a family of algorithms, encapsulates each algorithm, and makes them interchangeable. It lets the client algorithm vary independently from the objects that use it. This pattern is useful when you have a family of algorithms and want to make them interchang
11 min read
Command Method Design Pattern in Java
The Command Design Pattern in Java is a behavioral design pattern that turns a request into a stand-alone object, allowing parameterization of clients with different requests, queuing of requests, and support for undoable operations(action or a series of actions that can be reversed or undone in a system). Important Topics for Command Method Design
10 min read
Null Object Method Design Pattern in Java
The Null Object Design Pattern is a behavioral design pattern that is used to provide a consistent way of handling null or non-existing objects. It is particularly useful in situations where you want to avoid explicit null checks and provide a default behavior for objects that may not exist. Important Topics for Null Object Method Design Pattern in
10 min read
Facade Method Design Pattern in Java
Facade Method Design Pattern is a structural design pattern that provides a simplified interface to a complex subsystem. It acts as a "front door," concealing the internal complexity of the subsystem and making it easier for clients to interact with it. In this article, we will get to know about what is Facade Method Design Pattern in Java, and why
9 min read
Flyweight Method Design Pattern in Java
A flyweight design pattern or flyweight method is defined as a structural pattern that is used to minimize memory usage or computational expenses by sharing as much as possible with other similar objects. The key idea behind the Flyweight pattern is to use shared objects to support large numbers of fine-grained objects efficiently. Important Topics
9 min read
Observer Method Design Pattern in Java
Observer Design Pattern is a behavioral design pattern where an object, known as the subject, maintains a list of its dependents, called observers, that are notified of any changes in the subject's state. This pattern is often used to implement distributed event handling systems. Important Topics for Observer Method Design Pattern How We can implem
11 min read
Abstract Factory Method Design Pattern in Java
The Abstract Factory Method Design Pattern is a creational design pattern that provides an interface for creating families of related or dependent objects without specifying their concrete classes. This pattern allows you to encapsulate a group of individual factories that have a common theme without needing to know the exact classes that will be c
8 min read
Bridge Method Design Pattern in Java
The Bridge Design Pattern is a structural design pattern that decouples an abstraction from its implementation so that the two can vary independently. This pattern is useful when both the abstractions and their implementations should be extensible by subclassing. The Bridge pattern allows us to avoid a permanent binding between an abstraction and i
6 min read