开发者

Design pattern to populate an object with xml

I have an object to populate with xml. I think that I might use a contructor which accept this xml to build the object. But, is there a better desi开发者_如何学运维gn pattern to do it ? Is it to the object to handle all the xml parsing ?

Thank you !


No you should not send the xml to the constructor because you are coupling the model with deserilizing logic. You should create a class that handles the deserlization for you and return an instance. Why this is important might be unclear. But imagine in the future you may have the data coming from a database, you don't want to pass the database connection to the constructor, do you? Instead you can create a different class that uses databases to generate an instance of your class.

Here are some good read:

http://en.wikipedia.org/wiki/Builder_pattern

http://en.wikipedia.org/wiki/Immutable_object


The simplest approach would be to let XmlSerializer do it for you. Just decorate it (if necessary) so that it knows how to map the xml, and call Deserialize.


if you receive XML as a string which requires special parsing, you can, I guess, create a manager/factory to construct your object:

           var myObject = MyObjectCustomXmlSerializer.Deserialize(xmlString);
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜