Friday, June 10, 2022

Design Pattern: Proxy Pattern

Chapters

Proxy Pattern

proxy pattern is a software design pattern. A proxy, in its most general form, is a class functioning as an interface to something else.

The proxy could interface to anything: a network connection, a large object in memory, a file, or some other resource that is expensive or impossible to duplicate. In short, a proxy is a wrapper or agent object that is being called by the client to access the real serving object behind the scenes.

Use of the proxy can simply be forwarding to the real object, or can provide additional logic. In the proxy, extra functionality can be provided, for example caching when operations on the real object are resource intensive, or checking preconditions before operations on the real object are invoked. For the client, usage of a proxy object is similar to using the real object, because both implement the same interface.

This diagram shows how to implement a proxy pattern Diagram
Courtesy of Wikipedia

This example demonstrates proxy pattern.
public class ClientCode{

  public static void main(String[] args){
    StringConcatInterface sci = 
    new StringConcatProxy(new StringConcat("My "));
    
    sci.concat("String!");
    System.out.println(sci.getText());
    sci.concat("String!String!");
    System.out.println(sci.getText());
    sci.concat("String!String!String!");
    System.out.println(sci.getText());
  }
}

interface StringConcatInterface{

  void concat(String str);
  String getText();
}

class StringConcat implements StringConcatInterface{
  private StringBuilder builder;
  
  StringConcat(String text){
    builder = new StringBuilder(text);
  }
  
  @Override
  public void concat(String str){
    builder.append(str);
  }
  
  @Override
  public String getText(){
    return builder.toString();
  }
}

class StringConcatProxy implements StringConcatInterface{
  private StringConcat sc;
  
  StringConcatProxy(StringConcat sc){
    this.sc = sc;
  }
  
  @Override
  public void concat(String str){
    if(sc.getText().length() > 10){
      System.out.println
      ("Max characters has been reached!");
    }
    else
      sc.concat(str);
  }
  
  @Override
  public String getText(){
    return sc.getText();
  }
  
}

Result
My String!
My String!String!String!
Max characters has been reached!
My String!String!String!
You might have noticed that proxy pattern is similar to decorator pattern. Their structure is similar but their purpose are not. We use decorator pattern if we want to add functionalities to a class while not affecting other related classes. We use proxy pattern if we want some kind of mirror that mirrors our class.

No comments:

Post a Comment