How should I organize a collection of Classes
I have a series of objects and each has meta-data associated with it. In the typical case, I have a class representing Object and Meta_Data and I can make Meta_Data an attribute of the Object.
+---------------+ +---------------+
| Object |--->| Meta_Data |
+---------------+ +---------------+
The issue arrises when I want to create a collection of Objects, each of which is associated with a particular instance of Meta_Data.
The Meta_Data needs to be able to access its own neighbors:
a[0] = Object();
a[1] = Object();
// a[0].meta needs to be able to interact with a[1].meta
a[0].meta = Meta_Data();
a[1].meta = Meta_Data();
If I just create a collection of Objects (with Meta_Data instances as 开发者_运维知识库attributes), then the Meta_Data instances are isolated and can only interact by going through the primary object. This seems less than ideal.
The only real alternative that I can think of is to create some container class that allows me to have:
- An ObjectStack attribute that contains a collection of Object instances
- A Meta_DataStack attribute that contains a collection of Meta_Data instances
- Some sort of interface that syncs up the two so that I can query the corresponding meta-data for any particular Object instance.
This again seems inefficient. So what is the best way to have to collections of objects that can be linked item-by-item?
What you have then is something like this:
[Object]--->[MetaData]<--+
| |
+--------+
Something needs to be in charge of connecting the MetaData objects and it can't be any one particular Object object. You need a Factory or Builder of some sort that puts everything together properly.
That doesn't mean that the Factory needs to maintain a reference to every instance of both classes that exist, it just needs to make the connections.
Object a = new Object();
Object b = new Object();
MetaData ma = new MetaData();
MetaData mb = new MetaData();
ma.setFriend(mb);
a.setMetaData(ma);
b.setMetaData(mb);
精彩评论