If I understand correctly your reasoning, your market sells SoldComputer
which are categorized according to a generic ComputerType
. Furthermore the ComputerType
pre-defines some characteristics of all the computers of that type.
Composition over inheritance
First, a Computer
is not a ComputerType
. But looking at the properties of these classes, it appears that my argument is only about a naming issue, because your ComputerType
could also be named GenericComputer
, in which case it would be less shocking.
But your ComputerType
is only a small part of the problem. Because sooner or later, you'll realise that a sold computer can also have some StorageType
(e.g. HDD, 1To) and maybe also some GraphicType
, and many other configurable options. And tomorrow, you may even have new type of components you are not even aware off (e.g. holographic beamer 2D/3D) but that fundamentally do not change the way you describe and categorize the SoldCompter
.
This is why you should prefer composition over inheritance: you could have association with other types of components. The big advantage, of your current approach is that if a user decides to extend the RAM of its SoldComputer
, he/she can choose just the matching ComputerType
and everything is fine.
If you'd go for inheritance, the SoldComputer
would have its CPU
and its memory
: if the user would change their value, it would be inconsistent with the categorisation. And maybe there is no copmuter type corresponding to the new categorisation...
Alternative
Another way to look at the problem is to have a class Computer
with all the fields that technically describe the computer (e.g. CPU, memory, disk, etc...):
- the set of computer types in the market would be populated with
Computer
but with only some relevant fields filled.
- the set of sold computers in the market would be populated with
Computer
having some owner.
The creation of a new Computer
to be sold could use the prototype design pattern. But as soon as it is done, there would be no relation anymore between the computer and the prototype.
In this case, the market would no longer be categorised by compter type. The search would always be dynamic (eventually initialised using a choice list of the prototypes.
