I need to create a system with polymorphic objects.
Each type of object should be handled by a specific handler therefor I need to determine what is the type to handle it correctly.
I'm wondering what would be the best design decision:
Create an abstract base class something like ObjectBase
, and then extend to specific object, like CustomObjectA
and CustomObjectB
Create a generic object GenericObject
and use $type
property passed to the constructor (the type
should be immutable).
Note that the object don't differ, just the way they are handled, I mean, there no added property or method or anything in their behavior.
Any feedbacks?
EDIT:
First solution
abstract class ObjectBase {}
class CustomObjectA extends ObjectBase {}
class HandlerManager {
public function process(ObjectBase $object) {
if ($object instanceof CustomObjectA) {
$customObjectAHandler->process($object);
}
}
}
Second solution
class GenericObject {
protected $type;
public function __construct($type)
{
$this->type = $type;
}
}
class ObjectTypeAHandler {
public function process(GenericObject) {
}
public function supportsType(GenericObject $object)
{
return 'typeA' === $object->getType();
}
}
class HandlerManager {
public function process(GenericObject $object) {
if ($customObjectAHandler->supportType($object)) {
$customObjectAHandler->process($object);
}
}
}
Have all handlers share a base class. Have the object create the correct handler with a factory method that is abstract on the base class.
I would recommend you 1st way. It is not too hard to create 2 objects without body, but if you want to change their behavior in future - you will have things to get it done.