简体   繁体   English

用于从更复杂的对象构建对象的设计模式

[英]Design Pattern for building an object from a more complex object

I'm in the middle of refactoring some code on my current project, and I'd like some input on if any design pattern exists for the following scenario. 我正在重构当前项目中的某些代码,并且希望就以下情况是否存在任何设计模式提供一些意见。

I have a class which executes some logic and returns an object containing the results of said logic; 我有一个执行一些逻辑并返回包含上述逻辑结果的对象的类; Let's call this the Result object. 我们将此称为Result对象。 The state information contained in the Result object is constructed based on a more complex object, the Intermediary object. Result对象中包含的状态信息是基于更复杂的对象Intermediary对象构造的。

Now the code which populates the Result object from the Intermediary object already exists, but since I'm refactoring I want to make this cleaner. 现在,已经存在用于从Intermediary对象中填充Result对象的代码,但是由于我要进行重构,所以我想使它更整洁。 I was thinking of creating a separate class, maybe called ResultBuilder, which has a static execute method which takes Intermediary as input and spits out Result as output. 我当时正在考虑创建一个单独的类,可能称为ResultBuilder,该类具有静态的execute方法,该方法将Intermediary作为输入,将Result作为输出。

Is there a design pattern which is equivalent to the "ResultBuilder" class? 是否有一种等效于“ ResultBuilder”类的设计模式? Is there a better way of going about constructing a Result object from an Intermediary object? 从中间对象构造Result对象是否有更好的方法?

相信您需要Factory模式。

It seems that you already have the solution, So why do you find the need to have some external source to name it for you so it will become more valid? 看来您已经有了解决方案,那么为什么您发现需要一些外部来源来为您命名,这样它才变得更加有效?
If it makes sense to you and indeed makes things clearer and cleaner, just do it without excessive thinking about names and labels. 如果这对您有意义,并且确实使事情变得更清晰和整洁,则无需过多考虑名称和标签就可以做到这一点。

为什么Result不能具有采用Intermediary实例的构造函数?

The Builder pattern! 生成器模式!

though its usually a multi part build process....if it just makes one thing, then its more of a factory.... 虽然它通常是一个多部分的构建过程。...如果只制造一件事,那么它更多的是工厂。

its a standard GOF pattern 它是标准的GOF模式

I would suggest looking into the Builder and Factory patterns, both of which are Gang of Four patterns. 我建议研究一下BuilderFactory模式,它们都是“四个帮派”模式。 There are examples on Wikipedia of both, and in Java no less. 在Wikipedia上都有例子,在Java中也不少。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM