简体   繁体   中英

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. The state information contained in the Result object is constructed based on a more complex object, the Intermediary object.

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. 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.

Is there a design pattern which is equivalent to the "ResultBuilder" class? Is there a better way of going about constructing a Result object from an Intermediary object?

相信您需要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

I would suggest looking into the Builder and Factory patterns, both of which are Gang of Four patterns. There are examples on Wikipedia of both, and in Java no less.

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