I have a problem trying to design some generic storage..
Basically I have the following 4 objects
Pallet
Box
Parcel
Item
The top 3 are all containers, which can contain anything lower in the heirarchy than itself.
Initially, it was forced so that Pallets contain boxes, boxes contain parcels, parcels contain items.
But now I want it so some of the ‘middle’ containers can be skipped:
EG, Pallets contain Parcels which contain Items (no cartons)
EG2, Pallets contain Items (no Cartons or items).
At the moment I have a database table for each of these objects.
But it’s becoming messy to design a way to keep track of everything.
In Code, I’m presented with other problems, eg to print the contents of a pallet, initially would be:
class Pallet : List<Box> {}
class Box : List<Parcel> {}
class Parcel : List<Item> {}
class Item {}
class Pallet : List<Box>
{
void Print()
{
foreach (Box b in this)
foreach (Parcel p in b)
foreach (Item i in p)
//Print
}
}
But now since I dont know what will be inside, I’m not sure how to go about it.
I’m hoping someone can give me advice on designing a good data structure or method of storing everything in a good and efficient manner.
I could do something like:
class Pallet : List<T>
{
void Print()
{
if (this[0] is Box)
//do this
if (this[0] is Parcel)
//do this, etc
}
}
But it seems horribly messy.
I hope you can see what I am trying to do.
Why can’t you simply derive each container from the exact same base class? Then you could have something like the following:
This means that any container can contain a number of other containers. Of course you will need to implement some logic to control this, you don’t want a Box containing too many Parcels, but a Box could contain another box provided it was smaller. Now you would say “but Item would have to also inherit from COntainer to be contained within a Box”, and you would be right, but you can still use inheritance and a simple small change:
Using this approach means a
Palletcan contain things, but it cannot be contained. AnItemcan be contained but isn’t a container.You can also store all your containers in the same self-referencing database table – they don’t need to be separated out. Each contained item can simply have a foriegn key back to another entry in the same table that is its container.