开发者

Using a Builder class to recreate child object set using DI?

I have a Request class that is used to retrieve a file resource from an external process, using a method R开发者_运维技巧etrieveResource(). This method takes approximately 10-15 seconds to complete. In addition, the Request class contains four child objects, which are instantiated using dependency injection during the construction of the class, to access the contents of the requested file.

The Request class is instantiated from the main class of the project. The main class calls RetrieveResource() approximately every 30 seconds. After each invocation, it may be necessary to adjust a particular property, for example, Property A, of one or more of the child objects of the Request class.

I would be interested to hear views of the best way to accomplish this. The following list describes three approaches that could be used to change the value of Property A:

  1. The main class explicitly sets the value of Property A on each child object of the Request object by calling the property directly. For example, Request.Object1.PropertyA = newValue;

  2. Create a method in the Request class to update the value of Property A on each child object, for example, UpdatePropertyA()

  3. When creating an instance of the Request class, pass a builder class that is responsible for creating a new Request instance, including the creation of the each of the four objects using DI. The builder class contains a property, for example, Property A, which is then used to set the value of the property of the name for each child object of the Request class.

Grateful to hear thoughts. Thanks.


The problem with first two approaches you have suggested is that they are not flexible. If later your requirements would change (say you will have more child objects, or property A will be simply renamed, etc.), this will cause changes in the main class or in the Resource class, which is not good. Moreover, from my point of view this is not the job for these classes to update property A.

Personally I would suggest slightly modified third approach, because it moves all the update logic to the builder object, which is a good and flexible solution. I would say that this object should have a method, say BuildUp(Request instance), and inside this method all the update should take place. The way that you implement the actual update does not matter here - it will all be left aside in a special class, and in case of any change it could be modified in a blink of an eye, without changing the main logic of the application classes.

Furthermore you might want to create an interface for this builder, and operate with interface only in code of Resource class. It will be the main class who will know about the actual implementation of the builder being used. That way it would be a matter of a single line to substitute the implementation of the builder in case of any changes.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜