'Design pattern for object containing sets of other objects

I have a complex structure of classes Hero, Castle, Artefact and Position. They are in the following relationships:

  • A Position can contain several or none Heroes, while a Hero can be only on one Position.
  • A Castle belongs to one Hero and can be built on one Position. A Hero can have 0-1 Castles. A Position can have 0-1 Castes as well.
  • An Artefact can either be buried in a Position or can be equipped by a Hero. Thus, Artefact has reference to 0-1 Heroes and 0-1 Positions. A Hero can have 0-1 Artefacts and a Position can contain 0-1 Artefacts as well.

Now, to implement those both-way relationships, it is difficult to always change the references in all affected objects (e.g. when a Hero equips an Artefact, I have to change Hero.Artefact, Artefact.Hero, Artefact.Position and Position.Artefact). Therefore, I am using a Game class, that serves as a container for all of them (in other words, the Game class has 4 lists, one for each class).

Then, I add the reference just to the containing Game and with the help of IDs I am able to change the individual references much more elegantly (equipping the Artefact again):

Artefact.HeroID = newHeroID;
Artefact.PositionID = null;

All the accessors in the respective classes then allow me to get the right object(s):

Hero.Artefact
{
    get
    {
        return this.Game.Artefacts.FirstOrDefault(a => a.HeroID == this.ID);
    }
}

Artefact.Hero
{
    get
    {
        return this.Game.Heroes.FirstOrDefault(h => h.ID == this.HeroID);
    }
}

etc.

Is there a name for this design pattern (is it a design pattern)? It is really hard to find the right answer, when you know the implementation, but don't know the name :D (the other way around is quite simple).



Solution 1:[1]

For me it looks like a repository pattern from Domain Driven Design with in memory implementation in that case.

Repository is a magic shelf from where you get your domain objects (like your Hero, Artefact). How it's done is irrelevant for client of repository, you can pass there MySQL implementation, file, redis etc. In your case it's a simple in-memory storage.

More info: http://martinfowler.com/eaaCatalog/repository.html

Solution 2:[2]

There is NO ONE design pattern to solve your business problem. Those patterns are just documented implementation approaches that encourage reuse. I'd suggest you give this a read https://dofactory.com/net/design-patterns Probably the most readable and concise tutorials around. It may give you some insights and direction to your problem.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Rafa? ?u?y?ski
Solution 2 user2695439