This example is highly contrived so bear with me.
I have two Java classes, Chair and Desk, which are coming from a third party (i.e. I can’t change them).
public class Chair {
//...
}
public class Desk {
//...
}
For each of these classes, I need to run a method, doWork(), which depends on DatabaseService. My approach is to create an adapter which implements the OfficeFurniture interface for each class.
public class ChairAdapter implements OfficeFurniture {
//...
}
public class DeskAdapter implements OfficeFurniture {
//...
}
public interface OfficeFurniture {
public doWork(DatabaseService databaseService);
}
Finally, the question: Is it better to pass DatabaseService in the doWork() call, or to pass it in the constructors for ChairAdapter and DeskAdapter and store an instance in the class fields? Or is there another better approach?
It depends, should the client of the adapter know anything about the database service? Probably not, so you put it in the constructor. If the client has to know something about the database service, then passing it is better.