I have to produce a class diagram for a condition, condition was something like:
Fruits have colors and fruits can grow. Apples are fruits.
They have seeds. Seeds can make new apples.
I would like to have some experts advice before I implement any design.
I was thinking some thing like this but I am no expert so please help me out here
abstract class Fruit
{
protected $_color;
abstract function grow();
protected function seed(Fruit $fruit)
{
return $fruit;
}
}
class Apple extends Fruit
{
}
How can this be achieved using composition or inheritance ?
There are fruits that have seeds. Apple is one of those fruits. So I would use a simple plain inheritance design:
In this way you cannot reuse the implementation of the grow method of a non-
SeedableFruitin aFruitwith seeds, but if you think how natural evolution works, it makes sense… because in that case the two fruits have a common ancestor that grows in the same way, so the problem could be resolved inserting that common ancestor in the class hierarchy.The alternative design was to use a DecoratorPattern to describe a fruit that can have seeds, and then create an Apple with seeds with a call like
new SeedableFruitDecorator(new Apple());. But I think it’s not the correct way, since an Apple has always seeds.