Proxy Design Pattern in JAVA #6

Reading Time: 2 minutes

In this blog, we will discuss Proxy Design Pattern, its example, and how it is different from the other design patterns. But, it’s important to have an understanding of the design patterns first. You can refer here.

What is a Proxy

A Proxy is something that has the authority to do some activity on behalf of the original object. For example, when you are busy for the day and you have to pay electricity bill. So, your approach would be like you will ask someone else to pay on behalf of you.

Proxy Pattern

In the proxy patterns, a class represents the functionality of another class. These type of design patterns comes under structural patterns. Here, we create an object having original object to interface its functionality to outer world.

Why we need Proxy Pattern

This proxy is helpful when we don’t want to manipulate our main object. It avoids the duplication of objects so less memory is used which turns out to increases the performance of the application. And one of the advantages of Proxy pattern is good security.

Example for Proxy Pattern

Let’s see how to write a program using the Proxy Pattern.
So we start by creating a simple interface.

public interface College  {

    public void attendance(String student) ;

}

Now let’s use this interface to create a orignal class.

public class OriginalStudent implements College {

    @Override
    public void attendance(String student) {
        System.out.println(student + " is present in class");
    }
}

Now moving on we will create an proxy class using same interface.

public class ProxyStudent implements College{

    private College college = new OriginalStudent();
   
    @Override
    public void attendance(String student)  {
        if(student=="Nikunj"){
            System.out.println("Banned Student");
        }
        else
            college.attendance(student);
    }
}

Now use the Proxy class in place of Original class.

public class ProxyPatternExample {
	
  public static void main(String[] args) {
            College college = new ProxyStudent();
                college.attendance("Addi");
                college.attendance("Nikunj");
    }
}

and Output will be:

Addi is present in class
Banned Student

That’s pretty much it from the article. If you have any feedback or queries, please do let me know in the comments. Also, if you liked the article, please give me a thumbs up and I will keep writing blogs like this for you in the future as well. Keep reading and Keep coding.

References

Written by 

I am a genius middle-class noble philanthropist(by heart) . & Simply a technology enthusiast who loves to share and gain knowledge through blogs.