I am learning a lot about design patterns when I am building my own system for my projects. And I want to ask you about a design question that I can't find an answer to.
Currently I am building a little Chat-server using sockets, with multiple Clients. Right now I have three classes:
I have made a diagram to illustrate it:
I have a list of persons on the server in the Hotel-class because it would be nice to keep track of how many there are online right now (Without having to iterate through all of the rooms). The persons live in the Hotel-class because I would like to be able to search for a specific Person without searching the rooms.
Is this bad design? Is there another way of achieve it?
Thanks.
I don't like it. A hotel contains rooms, and rooms contain people. People don't contain rooms, they belong to them.
You don't necessarily have to iterate to get your guest count. You could just keep a running count ($Hotel->total_guests) and modify it as it changes.
The mutual dependency problem among the classes, strictly speaking, can be solved by using interfaces (abstract classes, if your language is e.g. C++ or Python) IRoom
and IPerson
; in pseudocode
interface IPerson
IRoom getRoom()
// etc
interface IRoom
iter<IPerson> iterPerson()
// etc
this makes only the interfaces mutually dependent on each other -- the actual implementations of the interfaces need only depend on the interfaces.
This also gives you plenty of leeway in terms of implementation, if you want avoid circular reference loops (which can be a bother e.g. in CPython by slowing down garbage collections) -- you could use weak references, an underlying relational database with a typical "one to many relationship" table, etc, etc. And for the first simple prototype you can use what's simplest in your chosen language (probably simple, and alas necessarily circular, references [[pointers, in C++]] with a Person
referring to a Room
and a Room
to a list<Person>
).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With