TwilightSun
TwilightSun

Reputation: 2335

Is there any better alternative way to the strategy pattern in Java?

I have two sets of Java API's doing the same job but targeting different system platforms, all their API function definitions are exactly the same except that they have different package names (and they do not implement the same interface). I'm not free enough to change the code of the API, so I can not make them implement any interface.

I want to write code above these APIs and want to have these code to be usable for both API sets (similar to the strategy design pattern).

What is the best way to achieve this? I do not want to make a interface and adapter classes because there are over 20 API methods.

Upvotes: 2

Views: 456

Answers (2)

Peter Kofler
Peter Kofler

Reputation: 9448

Despite being not what the original question wants, I would go with the Adapters for both APIs. Your Adapters would implement your own interface and could be used in a Strategy then.

This also gives you the option to come up with your own interface and descriptive names for the actions you need and completely abstract away the underlying APIs. Maybe you do not need all 20 methods?

Hints:

  • In Eclipse there is the function in the Source menu to generate delegate methods which would create the 20 delegating methods for you as soon as you have a field of the type you want to delegate to.
  • To extract the interface you can use the function Refactor/extract interface which creates and implements the interface.

An alternative approach would be to use java.lang.reflect.Proxy (as explained by Beryllium). The implementation of the proxy is straight forward but you need to create the interface up front by hand.

Upvotes: 5

Beryllium
Beryllium

Reputation: 12998

You could use a dynamic proxy (java.lang.reflect.InvocationHandler), but this requires additional classes/interfaces as well. A dynamic proxy in this scenario would just reduce the number of methods you have to implement/delegate from 20 to 1 at the cost of reflection.

It has already been commented by Keppil that there is no way to get this "for free" in standard Java, because the standard Java way is to use an interface (you are looking for Groovy's duck typing).

Upvotes: 2

Related Questions