Proxy Pattern
Photo by Petter Lagson on Unsplash

Proxy Pattern

Ever wondered how you can manage heavy resources in your applications without slowing down performance? There is way to initialize them only when you need them.

You can use the Proxy Pattern…

Imagine you have a friend who is very busy and important. Instead of calling them directly, you might call their assistant who handles some tasks before involving your friend.

THE WHAT

The Proxy Design Pattern is like having a stand-in or a representative for another object. Imagine you have a friend who is very busy and important. Instead of calling them directly, you might call their assistant who handles some tasks before involving your friend. This assistant is a proxy. In programming, a proxy controls access to another object, allowing you to add extra steps before or after the real object does its job.

THE PROBLEM IT?SOLVES

Sometimes, you have objects that are heavy to create or use a lot of resources. Creating these objects right away can slow down your program. You only want to create them when necessary, but you don’t want to add extra code everywhere to handle this. This can lead to code duplication and errors.

Example Problem

Imagine you have an application that interacts with a database. Establishing a database connection can be slow and resource-intensive if done immediately, even if the user doesn’t perform any database operations right away. You want to establish the connection only when the user requests data.

THE WHEN

You can use the Proxy Pattern in situations like:

  • Lazy Initialization: Create the object only when it’s needed.
  • Access Control: Allow only certain users to access the object.
  • Remote Access: Represent an object that is in a different location, like on another server.
  • Logging: Keep track of all requests to the object.
  • Caching: Store results of expensive operations to reuse them later.
  • Smart References: Perform extra actions when an object is accessed.

How to Implement the Proxy?Pattern

Let’s use the example of a database connection. We’ll follow these steps:

Step 1: Define the Service Interface

The interface defines the methods that the real object and the proxy will use.

public interface Database {
    void query(String sql);
}        

Step 2: Create the Real?Object

This class implements the interface and contains the actual logic for connecting to the database and executing queries.

public class RealDatabase implements Database {
    private String connectionString;

    public RealDatabase(String connectionString) {
        this.connectionString = connectionString;
        connect();
    }

    private void connect() {
        System.out.println("Connecting to database with connection string: " + connectionString);
        // Simulate database connection setup
    }

    @Override
    public void query(String sql) {
        System.out.println("Executing query: " + sql);
        // Simulate executing a query on the database
    }
}        

Step 3: Create the Proxy?Class

This class also implements the interface and controls access to the real object. It creates the real object only when it’s needed.

public class ProxyDatabase implements Database {
    private RealDatabase realDatabase;
    private String connectionString;

    public ProxyDatabase(String connectionString) {
        this.connectionString = connectionString;
    }

    @Override
    public void query(String sql) {
        if (realDatabase == null) {
            realDatabase = new RealDatabase(connectionString);
        }
        realDatabase.query(sql);
    }
}        

Step 4: Implement the?Client

The client code interacts with the proxy as if it’s the real object. The proxy handles creating the real object when necessary.

public class ProxyPatternDemo {
    public static void main(String[] args) {
        Database database = new ProxyDatabase("<Connection_String>");

        // Database connection will be established and query will be executed
        database.query("SELECT * FROM users");

        // Database connection is already established, only query will be executed
        database.query("SELECT * FROM orders");
    }
}        

Pros

  • Control Access: The proxy can control access to the real object, adding extra steps like logging or access control.
  • Lazy Initialization: The proxy can delay creating the real object until it’s actually needed, saving resources.
  • Simplified Code: The client code remains simple, as it interacts with the proxy in the same way it would with the real object.

Cons

  • Increased Complexity: Adding proxies can make your codebase more complex with additional classes.
  • Potential Delays: Accessing the real object through a proxy might introduce some delays, especially if creating the real object is time-consuming.

Conclusion

The Proxy Design Pattern is a useful tool for managing access to resource-intensive objects and adding extra steps like caching, logging, or access control. By understanding the problem it solves, when to use it, and how to implement it, you can leverage this pattern to create more efficient and maintainable software.

Thank you

要查看或添加评论,请登录

Chirag Vaswani的更多文章

  • Iterator Pattern

    Iterator Pattern

    WHAT IS ITERATOR PATTERN? Iterator pattern allows us to traverse elements of a collection without exposing its…

  • Command Pattern

    Command Pattern

    The Command design pattern encapsulates a request as an object, thereby allowing users to parameterize clients with…

  • Chain of Responsibility Pattern

    Chain of Responsibility Pattern

    Ever faced challenges managing complex workflows with multiple handlers in a serial manner? CoR to the rescue… THE WHAT…

  • Flyweight Pattern

    Flyweight Pattern

    Flyweight is a class in boxing which includes fighters weighing up to and including 51 kg (112 lb) for a title fight…

  • Facade Pattern

    Facade Pattern

    The What The Facade Pattern is a structural design pattern that provides a simplified interface to a complex subsystem,…

  • Decorator Pattern

    Decorator Pattern

    The Decorator Pattern is a structural design pattern that allows you to dynamically attach additional responsibilities…

  • Composite Pattern

    Composite Pattern

    Have you ever struggled with managing complex hierarchical structures in your code? Composite pattern can simplify your…

  • Bridge Pattern

    Bridge Pattern

    Ever felt overwhelmed by the explosion of subclasses when trying to support multiple variations in your code? What if…

  • Adaptor Pattern

    Adaptor Pattern

    The Adapter Pattern is about creating an intermediary abstraction that translates, or adapts, one interface into…

  • Singleton Pattern: A Comprehensive Guide

    Singleton Pattern: A Comprehensive Guide

    The Singleton Pattern is one of the most widely used design patterns in software engineering. Whether you are working…