How to implement a dynamic list of builders?

I am writing code that creates a UserProfile object from Map of Strings. I am currently dividing the code into several Builder objects that create parts of a user profile, something like this:

public UserProfile getUserProfile(int id) {
  Map<String, String> data = this.service.getUserProfileData(int id);
  UserProfile profile = userProfileBuilder.build(data);
  profile.setMarketingPreferences( marketingPreferencesBuilder.build(data) );
  profile.setAddress( addressBuilder.build(data) );

  ...

  return profile;
}

It would be nice to have a list of builder objects instead, so that I can dynamically add additional collectors without touching the class and breaking OCP .

Maybe something like this:

private List<ProfileBuilder> builders;

public void buildBuilders() {
  this.builders = new ArrayList<ProfileBuilder>();
  builders.add( new BasicDetailsBuilder() );
  builders.add( new AddressBuilder() );
  builders.add( new MarkettingPreferencesBuilder() );

  ...

}

public UserProfile getUserProfile(int id) {
  Map<String, String> data = this.service.getUserProfileData(int id);
  UserProfile profile = new UserProfile();
  for(ProfileBuilder builder : this.builders) {
    builder.build( profile, data );
  }

  return profile;
}

Do you have problems with this approach? Is it strictly a Builder Design Template?

+5
source share
2 answers

Use builder / builders only if the UserProfile construct is complex

Map UserProfile, UserProfile, , - : : Map → setter method UserProfile

+1

, . :

interface UserProfileVisitor {
  public void visit(UserProfile profile, Map<String, String> data);
}
+2

All Articles