# Proxy

In 
Published 2022-12-03

This tutorial explains to you the design pattern named Proxy (which is a Structural Pattern).

# Proxy Pattern - theory

Proxy Design Pattern in Java is used when we want to create a wrapper that control the execution of the methods from another class. Take a look at the following UML diagram representing the Proxy design pattern (for my example):

In Proxy Design Pattern, the main idea is to control the execution of some methods from another class.

# Proxy Pattern - example

Here is that example using the Proxy Design Pattern in Java:

package proxy.java.pattern.example;
 
public interface Car {
 
  // This method build a car.
  public void build();
   
  //This method paint a car.
 public void paint();
 
}
package proxy.java.pattern.example;
 
public class Renault implements Car{
      
    public void build(){
        System.out.println("A Renault car has been built.");
    }
     
    public void paint(){
        System.out.println("A Renault car has been painted.");
    }
     
}
package proxy.java.pattern.example;
 
public class RenaultProxy implements Car{
      
    private String userName;
    private Renault renault;
     
    public RenaultProxy(String userName) {
        super();
        this.userName = userName;
        renault = new Renault();
    }
 
    public void build(){
        renault.build();            
    }
     
    public void paint(){
        if (userName == "John") {
            System.out.println("A Renault car CANNOT be painted by John !");
        } else {
            renault.paint();    
        }
    }
     
}
package proxy.java.pattern.example;
 
public class ProxyJavaPatternExample {
     
    public static void main(String[] args){
        RenaultProxy renaultProxy1 = new RenaultProxy("John");
        renaultProxy1.build();
        renaultProxy1.paint();
         
        RenaultProxy renaultProxy2 = new RenaultProxy("Dana");
        renaultProxy2.build();
        renaultProxy2.paint();
    }
}

When you run this example you will receive the following result: