vendredi 12 mai 2017

Deciding Which Class to Return in Factory

I'm creating a Product abstract class, which is supposed to be subclassed according to the product category (each category has different internal logic but same interface, hence I chose to go with abstraction model). However, I want the user to call a factory method which decides what subclass to return automatically. First, is it bad practice to include this factory method in the abstract class itself?

abstract class Product
{
    abstract public function getDescription();
    abstract public function getValue();

    public static function
    createProduct($category)
    {
        return # ...
    }
}

How can I decide which subclass to return? Of course I could do a switch-case:

switch($category) {
    case PROD_BOOK:
        return new Book();
        break;
    case PROD_FOOD:
        return new Food();
        break;
}

But this kind of hard codes the classes. When adding a new product, I'd have to add the new constant for the category and modify the factory logic. I'd like to keep the factory logic intact. Is there any way to make a table of category keys and class references as values? So I could do something like:

return new ($classes[$category])();

Then I just need to update the $classes array when adding new products.

Aucun commentaire:

Enregistrer un commentaire