简体   繁体   中英

Proxy pattern concrete class hiding implementation details

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 ?

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 (ie 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM