简体   繁体   中英

Same interface, implementation differences

Given: - Different implementations that need to be gathered under the same interface

Unluck: these implementations have a method 'create', but with different number and types of input params

Solutions....? What other option is there besides varargs of Object?

Assuming that you want only one create method under the interface that you are intending

Create a wrapper class that implements the interface you are intending. Now call the various implementation from wrapper class based on some condition.

For Maintainabilty Perspective

If possible avoid conditions and Send the implementation class name from calling code .just call the create method on class passed as argument from calling code.(For this you also need to create the dummy create method with some object class as parameter which contains all the parameters under each implementation class which simply delegates the call to intended method with required number of params )

If the method is so flexible there seems little point in trying to enforce it via an interface . What you could do, though, is implement an interface describing the different types of parameters you want to pass.

eg

public abstract create(CreateParamsInterface cpi) {};

and then implement that abstract method in your class, using the members exposed va CreateParamsInterface as relevant.

In the interface provide a method that takes a condition as an argument on basis of which you can decide which version of create you wish to call. Based on the condition you can call the respective create() function.The logic is same as that of the Factory design pattern .

I see three options:

  1. You can pass parameters when you construct object which has method create() . So you just add parameters to constructor of object which implements interface containing create() .
  2. Modify create so that it will take as argument the object which calls method create() . That way you should have interface create(ObjectWhichWantsCreation x) and this method would take all necessary data from given object.
  3. Make create(Properties p) where Properties: http://docs.oracle.com/javase/6/docs/api/java/util/Properties.html this is quite generic but you must make sure that they contain needed data.

of course you can modify 2 and 3 so that they have method create() and just add another method setParams(SomeParams...) which needs to be called first.

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