how to avoid storing different type of objects in the same place when they represent the same but with a different data structure
This is in my opinion an abstract problem and I hope I can explain it well. I happened to find the same kind of problem in a completely different project and now I have it again and I would like to avoid it if possible.
I'm creating some classes to simplify some tasks for some specific requirements we have in some projects at work.
I have a class that creates objects which maps the values from webcontrols to an object properties similar to this
http://msdn.microsoft.com/en-us/library/aa478957.aspx
The problem I have it's sometimes I have to store a non container object in a p开发者_如何学JAVAlace (in an object's attribute) and sometimes I have to a store a container object in the same place for storing the values of a webcontrol (a webcontrol can sometimes hold several values like a checkboxlist). I dont like this at all, because some time ago when working in a non commercial compiler, when parsing and generating the intermediate code I had sometimes to store a container in a place, and sometimes I had to store a non container in the same place, and having to ask in other parts of the code if what you are reading is this type of object, or this another type of object, it is something really annoying and it mess up the code. Is there any tips about what it would be better to do to avoid this kind of situations or nothing can be done to avoid it sometimes?
This is the Polymorphism problem.
"sometimes I have to store a non container object in a ... an object's attribute and sometimes I have to a store a container object in the same place"
You have two things which should be made polymorphic.
The easiest way to fix this is to use a container always. When you want to store a single non-container object, you "wrap" it in a container that contains just the one object.
Then you always have containers. Sometimes the container has one object, sometimes it has more than one.
I'm not sure I understand your question, but maybe Visitor pattern is what you are looking for?
Sounds like composite pattern to me. Composite will provide an interface for treating containers of objects and leaf objects (those that are not containers) the same.
精彩评论