Hello, I've been pondering the best way to implement a certain kind of functionality... that being derived objects referencing other derived objects with the same base (including mutual referencing).
Below is the best (simple) example I could think of to illustrate the kind of problem: a house made up of 3 rooms (though in practice it could be hundreds) each represented by its own derived class. Of course it won't work as it stands, it would cause a stack overflow (appropriately!)
Assuming each room in the example is specific to a room in an imaginary house, there should be no more than one instance of any subclass. Constructing lots of instances, even without the recursion, would be messy. That would make me think singleton if that weren't such a taboo... can anyone suggest something more appropriate?
Thank you!
public abstract class Room
{
abstract public void DoAction();
public Room[] ConnectedRooms;
}
public class Kitchen : Room
{
public Kitchen() { ConnectedRooms = new Room[] { new Hall() }; }
public override void DoAction() { MakeTea(); }
}
public class Bedroom : Room
{
public Bedroom() { ConnectedRooms = new Room[] { new Hall() }; }
public override void DoAction() { Sleep(); }
}
public class Hall : Room
{
public Hall() { ConnectedRooms = new Room[] { new Hall(), new Bedroom() }; }
public override void DoAction() { LookOutWindow(); }
}