What is Proxy pattern? Explain with example.
What is Proxy pattern? Explain with example.
Proxy pattern is a structural pattern where a class represents the functionality of another class. A proxy, in its most general form, is a class functioning as an interface to something else. Proxy pattern intent according to GoF is “Provide a surrogate or placeholder for another object to control access to it”.
The following example demonstrates “Virtual Proxy” pattern. In the example, actual class is RealAudio and ProxyAudio is used as a proxy for RealAudio. Using the proxy pattern, the ProxyAudio avoids multiple loading of the sound from the disk in a memory-saving manner.
public interface Audio {
public void playAudio(); }
|
public class RealAudio implements Audio{
public RealAudio() { System.out.println(“Playing real audio…..”); } @Override public void playAudio() { System.out.println(“Playing audio….”); } }
|
public class ProxyAudio implements Audio{
RealAudio real; @Override public void playAudio() { if(real == null){ real = new RealAudio(); } real.playAudio(); } }
|
public class TestProxy {
public static void main(String[] args) {
Audio audio = new ProxyAudio();
audio.playAudio();
audio.playAudio();
}
}
Output:
Playing real audio…..
Playing audio….
Playing audio….
Proxy pattern can be used when one of the following is required in the application:
- The object being represented is external to the system.
- Objects need to be created on demand.
- Access control for the original object is required.
- Added functionality is required when an object is accessed.