I want to build a .jar that encapsulates a vendor api, so we can use our own objects as parameters to communicate with the api.
I've read some articles and topics here in SO, but I still am a bit confusing if I'm getting dependency injection right. For examples of House objects with Doors and Windows, it's easy to understand, but it seems it gets difficult with real code.
I didn't want to use any framework / locator pattern. The code below is just a simplification of how the objects are indeed. The Cake object is a big object and so on :)
Is this code fine? Should I change it in order to be easier to test?
//These are the third-party classes
class VendorService {
public VendorService(String wsdlPath) {/*vendor code*/}
ICakeApi getApi();
}
interface ICakeApi {
void authenticate(String username, String password);
VendorSpecificCake cookCake(VendorSpecificIngredients ingredients);
}
//This is the code I'm trying to use DI
class MyCakeService {
ICakeApi cakeApi;
public MyCakeService(ICakeApi cakeApi) {
this.cakeApi = cakeApi;
}
public void authenticate(MyUserPasswordBean bean) {
cakeApi.authenticate(bean.getUsername(), bean.getPassword());
}
MySpecificCake cookCake(MySpecificIngredients ingredients,
VendorObjectFactory vendorFactory,
InternalObjectFactory internalFactory) {
VendorSpecificIngredients objs =
vendorFactory.createVendorSpecificIngredients(ingredients);
VendorSpecificCake vCake = cakeApi.cookCake(objs);
MySpecificCake myCake = internalFactory.createMySpecificCake(vCake);
return myCake;
}
}
class MyCakeServiceFactory {
MyCakeService build(String wsdlPath) {
VendorService vendorService = new VendorService(wsdlPath);
ICakeApi cakeApi = vendorService.getApi();
MyCakeService service = new MyCakeService(cakeApi);
}
}
class UsageTest {
public void testMyCode() {
MyCakeServiceFactory factory = new MyCakeServiceFactory();
//should I add this as dependency on the constructor?
VendorObjectFactory vendorFactory = new VendorObjectFactory();
InternalObjectFactory internalFactory = new InternalObjectFactor();
MyCakeService service = factory.build("/tmp");
service.authenticate(new MyUserPasswordBean("john", "snow"));
MySpecificIngredients ingr = new MySpecificIngredients(...);
//ideally, I'd like to avoid having the user to instantiate
//VendorObjectFactory and InternalObjectFactory
service.cookCake(ingr, vendorFactory, internalFactory);
}
}