我应该如何实现构建器的动态列表?
我正在编写从字符串映射构建 UserProfile 对象的代码。目前,我将代码分成几个 Builder 对象,这些对象构建用户配置文件的一部分,像这样的东西:
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;
}
如果能够有一个构建器对象列表就好了,这样我就可以动态添加额外的构建器,而无需触摸类并破坏 OCP。
也许是这样的:
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;
}
你能看出这种方法有什么问题吗?这是严格意义上的 Builder 设计模式吗?
I'm writing code that builds a UserProfile object from a Map of Strings. At the moment I'm dividing the code into several Builder objects that build parts of the 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 be able to have a list of builder objects instead so that I can dynamically add additional builders without touch the class and breaking the OCP.
Perhaps something like this, instead:
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;
}
Can you see any problems with this approach? Is this strictly the Builder design pattern?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这更像是一个访客而不是一个构建者。你可以这样做:
This becomes more of a Visitor than a builder. You could do this:
仅当构建 UserProfile 很复杂时才使用 builder/builders
如果您只想将 Map 中的数据重写到 UserProfile 中的字段,并且 UserProfile 中有很多字段,也许更好的解决方案如下:反射和映射:来自 Map 的键 -> UserProfile 中的 setter 方法
Use builder/builders only if construction UserProfile is complicated
If you only want rewrite data from Map to fields in UserProfile and you have many fields in UserProfile maybe better solution will be something like: reflection and mapping: key from Map -> setter method in UserProfile