views:

45

answers:

1

Hi,

I have a while loop, and the user should be able to decide when the loop stops. After x seconds, after x loops, ... This problem should be implemented according to policy-based design. I know how to do this in C++ but can't get it to work in Java.

What I do now is the following.

There is a class Auctioneer with the method "start()" where the policies should be applicable:

public <E extends AbstractEndAuctionPolicy> void start(E policy) { //use policy here }

Because AbstractEndAuctionPolicy has the method "endAuction()", we are able to do: policy.endAuction(). In C++ there is no need for "extends AbstractEndAuctionPolicy" ...

But I can not figure out how to use this method, the following is not working:

this.auctioneer.start<NewBidPolicy>(n);

Hope you guys can help me and inform me a bit about policy-based design in Java because Google is not giving me answers.

Thanks in advance.

A: 

Usually the compiler is able to figure out the generic type from the parameter type, i.e. simply

this.auctioneer.start(n);

may work (it is hard to tell for sure, since you give so little context). But if this does not satisfy the compiler, try

this.auctioneer.<NewBidPolicy>start(n);

Since Java generics are so much less powerful than C++ templates, I haven't even heard the term "policy" being used much in the Java realm. However, your approach seems to be a good approximation.

Péter Török
Ok, I figured out that NewBidPolicy has to extend AbstractEndAuctionPolicy in the class definition. But now I don't see the advantage of generics anymore. It's just inheritance now?
@mrdckx, you are right, this is one of the ways Java generics is more limited than C++ templates. I.e. you must specify a superinterface in order to be able to call a specific method on a generic parameter object. So you have a good point indeed, in this case you can actually drop generics altogether and simply pass an `AbstractEndAuctionPolicy` parameter to `start()`.
Péter Török
Ok! Thanks for the fast replies.