0

I have been reading about java proxy pattern and invocation handler and everywhere it is seen that the concrete class construction is available to the client.

For example,

//TwitterService service = (TwitterService) SecurityProxy.newInstance(new TwitterStub());
TwitterService service = new TwitterStub();
System.out.println(service.getTimelinePosts("abc"));

User can create an instance of TwitterStub directly and access the methods. I was wondering if there was a way of not exposing the or avoiding the construction of the concrete class via the client ?

Is there a better way ?

Todd
  • 30,472
  • 11
  • 81
  • 89
Adithya
  • 2,923
  • 5
  • 33
  • 47
  • You need to provide an implementation of the InvocationHandler, nothing else is required. – Peter Lawrey Apr 08 '16 at 15:00
  • 1
    You can use the [Factory Method Pattern](https://en.wikipedia.org/wiki/Factory_method_pattern) or the [Abstract Factory Pattern](https://en.wikipedia.org/wiki/Abstract_factory_pattern) to hide the direct calling of your constructor. – callyalater Apr 08 '16 at 15:01
  • But I don't think I quite understand your question... – callyalater Apr 08 '16 at 15:04
  • Any dependency injection mechanism would seem to answer this question. – jaco0646 Apr 08 '16 at 18:25

1 Answers1

1

As the GoF puts it, the intent of the proxy pattern is "to provide a surrogate or placeholder for another object to control access to it".

So, in your specific case what happens is that you're creating a particular proxy instance directly. And that's fine as long as you (as a client) know that you want a particular type of proxy object.

If what you want is a level of indirection, you can use an Abstract Factory Pattern that return different types of proxy objects. But so far, the reason of proxy objects is to act on behalf of other objects.

As a side note, proxies are useful when you have objects that are expensive to create, but you don't want to necessarily cripple main application function due to such expense. For example, suppose you have a document with 1000 images. You can use proxies for them, and only load them when stricly needed (i.e. when they are in visible view), and you can still load the full document really fast without the overhead of reading 1000 images at once.

Jose Cifuentes
  • 596
  • 6
  • 21