The principle of Separation of Concerns is one of the main aspects of modern application frameworks like Spring or Hibernate. The intention is to separate the cross-cutting-concerns (e.g. database access, transaction management or security checks) from the implementation of the functional requirements. One possible solution to realize a transparent separation of concerns is to use the proxy design pattern. A proxy is some kind of wrapper, which controls the access to the interface of any object. Therefore the proxy implements the same interface as the wrapped object. By using the proxy pattern you're able to extend or change the behavior of an object without changing the object itself.
It's quite simple to implement the proxy pattern in Java. The so called JDK proxies are part of the Java API since version 1.3. All you need is the Interface InvocationHandler and the helper class Proxy. Let's take a look at a simple example. Given an interface:
There might be the following implementation of the interface for which you want to monitor the performance at runtime:
Instead of writing the performance-measuring-code directly into the service implementation we're separating this concern by using the proxy pattern. Therefor we implement the
That's it. Now we're ready to create of proxy. The proxy delegates method calls to the wrapped object.
Calling proxy.foobar() results in:
Invocation of method foobar() took 201 ms