最近我发现了一个构建器模式,这让我很感兴趣。
所以,我有一个 EntityBuilder
它构建了一个 Entity
,但它不返回实体。这是方法签名:
public void build();
相反,在 build()
中方法,它传递创建的新对象,Entity
, 到 CacheImplementation
实例来存储它。
注:CacheImpl
被注入(inject)到构建器的构造函数中。
public void build(){
//create new entity
cacheImplementation.add(entity);
}
这听起来像是最佳实践吗?
稍后编辑0
public interface EntityBuilder {
void setProperty0(PropertyObject propertyObject0);
void setProperty1(PropertyObject propertyObject1);
void setProperty2(PropertyObject propertyObject2);
//...
void build();
}
public class EntityBuilderImpl implements EntityBuilder {
PropertyObject propertyObject0;
PropertyObject propertyObject1;
PropertyObject propertyObject2;
//...
// setters for all properties
@Override
public void build(){
//create new entity
cacheImplementation.add(entity);
}
}
构建器的使用方式如下:
public class EntityProcessor{
private EntityBuilderFactory entityBuilderFactory;//initialized in constructor
void process(EntityDetails entityDetails){
EntityBuilder entityBuilder = this.entityBuilderFactory.getNewEntitytBuilder();
//..
// entityBuilder.set all properties from entityDetails
entityBuilder.build();
}
}
注意:cacheImpl 实例只是将实体存储在 List<>
中每 N 秒访问一次。
最佳答案
Does this sounds like best practice?
传统的构建器模式不会将创建的对象存储在任何地方,它只是返回它。
我可以想象一个变体,其中构建器还具有实例控制的作用,以避免创建重复的对象,并管理不可变对象(immutable对象)的存储。
不返回实例的决定可能是为了明确该方法有副作用。如果该方法返回了对象,它可能会误认为它是一个没有副作用的传统构建器,而实际情况并非如此。
无论如何,所有这些都只是推测,因为我们还没有看到使用它的其余代码以及它的实现和使用方式。我们没有足够的上下文来真正判断。 发明新模式并没有错,但可以做得好也可以做得不好。
关于java - builder 模式中的逻辑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32910446/