Java Design Patterns .

Java Design Patterns Proxy

Proxy (aka Surrogate) Overview - An example of a "Virtual Proxy"

One class controls the creation of and access to objects in another class.


PotOfTeaInterface.java - the Subject Interface

//PotOfTeaInterface will insure that the proxy 
//  has the same methods as it's real subject
public interface PotOfTeaInterface {   
   public void pourTea();
}
To download source right-click here and "Save As...".


PotOfTeaProxy.java - the Proxy

public class PotOfTeaProxy implements PotOfTeaInterface {  
   PotOfTea potOfTea;
    
   public PotOfTeaProxy() {}
   
   public void pourTea() {
       potOfTea = new PotOfTea();
       potOfTea.pourTea();
   }
}
To download source right-click here and "Save As...".


PotOfTea.java - the Real Subject

public class PotOfTea implements PotOfTeaInterface {  
   public PotOfTea() {
       System.out.println("Making a pot of tea");
   }
   
   public void pourTea() {
       System.out.println("Pouring tea");
   }   
}
To download source right-click here and "Save As...".


TestProxy.java - testing the Proxy

class TestProxy {
   public static void main(String[] args) {
       System.out.println("TestProxy: instantiating PotOfTeaProxy");
       PotOfTeaInterface potOfTea = new PotOfTeaProxy();
       System.out.println(" ");
       System.out.println("TestProxy: pouring tea");
       potOfTea.pourTea();
   }
}
To download source right-click here and "Save As...".


Test Results

TestProxy: instantiating PotOfTeaProxy

TestProxy: pouring tea Making a pot of tea Pouring tea

Notes

There are four types of proxies, all taking the same basic format:
1. Virtual Proxy - The proxy won't create an "expensive" subject object until it is actually needed.
2. Remote Proxy - A local proxy object controls access to a remote subject object.
3. Protection proxy - The proxy insures that the object creating/calling the subject has authorization to do so.
4. Smart reference - The proxy will perform "additional actions" when the subject is called.
Reference Desgin Patterns pages 208-209.

UML

UML for Proxy

References


online
Portland Pattern Repository
Books
Design Patterns by Erich Gamma, Richard Helm, Ralph Johnson, John Vlissides
Java Design Patterns - A Tutorial by James W. Cooper
Comments Comments are left by visitors to FluffyCat.com and may or may not be accurate.
Comment by archive on 2013-04-03 Rate this Comment

I think in your description of the proxy pattern in the class TestProxy.java is an error at line 8.

It should be written potOfTea.pourTe(); or ?

 
Sign in to comment on Java Design Patterns Proxy.