1. What is proxy?
Definition in Wikipedia is:
2. What is proxy pattern?
Proxy pattern provides a surrogate or placeholder for another object to access to it. It is something controlling the access to some resources and it doesn’t change the interface which clients use. That is, insteading of calling the thing we want, in proxy pattern, we call the thing(i.e. proxy) which calls the thing we want. So in proxy pattern, we define a seperate proxy that
- can be used as surrogate for another object and
- implements additional functinoality to control the access to this object.
3. What problem can proxy pattern solve?
- The access to a resource should be controlled.
- Additional functionality should be provided when accessing a resource.
4. Possible usage scenarios?
- Remote proxy: suggested to be used when you want to access a resource which is remote. Remote resouce coult be different server, different namespace, etc.
- Virtual proxy: controls access to a resource that is expensive to create. This is like caching.
- Protection proxy: is about access management, controls access based on access rights.
5. UML
wikipedia
In the above UML class diagram, the Proxy class implements the Subject interface so that it can act as substitute for Subject objects. In maintians a reference(realSubject) to the substituted object(RealSubject) so that it can forward requests to it(realSubject.operation()).
The sequence diagram shows the run-time interactions: The Client object works through a Proxy object that controls the access to a RealSubject object. In this example, the Proxy forwards the request to the RealSubject, which performs the request.
In summary,
Proxycontrols the access to th real subject.Proxyfollows the same interface as the thing it is proxying.Proxydoesn’t necessarily have to be passed the real subject upon the initialization (lazy evaluation).
6. Example
In this example, the LazyBookParserProxy is used to access an expensive resource BookParser. We first creates an interface IBookParser containing a method getNumberPages(). Then let a concrete class BookParser implements it. Using the proxy pattern, the code of the LazyBookParserProxy avoids multiple loading of the BookParser, accessing it in an expensive manner. The lazy loading demonstrated in this example is not part of the proxy pattern, but is merely an advantage made possible by the use of the proxy.
codes:
Interface IBookParser {
int getNumberPages();
}
Class BookParser: IBookParser {
public BookParser (string book) {
// expensive parsing
}
public int getNumberPages() {...}
}
Class LazyBookParserProxy : IBookParser {
private BookParser parser = null;
private string book = null;
public LazyBookParserProxy(String book) {
this.book = book;
}
public int getNumberPages(){
if (this.parser == null)
this.parser = new BookParser(this.book);
return this.parser.getNumberPages();
}
}