简体   繁体   中英

Adapter design pattern - dependencies in method calls or constructors?

This example is highly contrived so bear with me.

I have two Java classes, Chair and Desk , which are coming from a third party (ie 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.

If the DatabaseService class is a singleton or only needs to be instantiated once per Adapter class then pass in to the constructor; especially if you have multiple methods in each Adapter class that will use the DatabaseService instance. If it'll change between calls then pass it into the method.

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