Problem:
Problem:
I I need a limited amount of objects = instancesobjects = instances from a class, and I don't want to expose the option to create more. I also want easy access to them from everywhere, and operators like equal / not equal.
They need to be class instances, as they need to have methods, so an enuma enum doesn't work.
(Simplified) Example:
(Simplified) Example:
Consider Consider for example any chess-like game. (1) There are three tile colors for the board needed, Lighter and Darker, and a different size tile where taken pieces are put. Also, (2) the pieces have a color, typically White or Black; and I use NoColor for empty fields.
Both
- There are three tile colors for the board needed, Lighter and Darker, and a different size tile where taken pieces are put. Also,
- the pieces have a color, typically White or Black; and I use NoColor for empty fields.
Both examples, each instance should know how to draw and serialize itself.
Obvious Option:
Obvious Option:
If If I make a simple enum, the values cannot carry methods, so I end up with Draw and Serialize methods in some other class, which are basically an ugly switch/case.
My Solution:
My Solution:
I I like to a) protect the constructor, and b) create (public) static instances inside the class (C++17 now allows that even directly with inline). Each
- protect the constructor, and,
- create (public) static instances inside the class (C++17 now allows that even directly with
inline).
'Each instance gets created with a const 'type'const 'type' in it (basically an enuma enum), set through the constructor.
Wherever I need the information, I use the const pointerconst pointer to that static instancestatic instance. This allows to easily compare and assign_compare and assign them, and also allows tocalling their call their member functionsmember functions as needed.
It even allows other games to derive from the class and add new static instances, for example, a three player-player chess could add a Red instance inside a derived class. Because I hand around pointers to the base class everywhere, it is polymorphic, and the code doesn't have to handle the new color special in any way...
Question:
Question:
I I go back and forth in my mind between this being a code smell, or a pretty good and clean solution. So is it a code smell?
How else would this be better designed?