Is it possible for a wrapped object to "become" an object of the same type?
I have a wrapped XmlDocument class, and in it, I'd like to check to see if there's a cached XmlDocument object with the same name, and then "become" that object. Is there a better way to do this?
namespace myXmlUtilities {
class SpecificAutoLoadingCmsXmlDocument :开发者_JAVA技巧 System.Xml.XmlDocument {
private string documentName = "joiseyMike.xml";
public void loadFromCms() {
if (cache[documentName] != null)
LoadXml(((XmlDocument)cache[documentName]).OuterXml);
else
// ... load from the CMS's database.
}
public SpecificAutoLoadingCmsXmlDocument() {
loadFromCms();
}
}
Edited: I made the example a little more true-to life. Apologies for the earlier quick-and-dirty version.
You should use a factory pattern instead which would allow you to put this logic into the factory method(s).
So you'd end up with:
public static XmlDocument GetNewDocument(string documentName) {
if (cache[documentName] != null)
return cache[documentName];
else
return new XmlDocument();
}
So instead of doing a simple new XmlDocument();, you'd make a call to the static GetNewDocument() method.
I would rework the arch here. You are missing a seperation of concerns. Why not use a factory to check if the cache has that name and give you that object back? An object trying to construct itself seems messy to me.
精彩评论