A
A
atis //2016-08-08 17:08:00
OOP
atis //, 2016-08-08 17:08:00

Is it correct to use switch/case in the Factory Method pattern?

Hello.
Essentially a subject.
I'll give an example:

interface House
{
    public function build();
    public function demolition();
}

class BlueHouse implements House
{
// реализация
}

class RedHouse implements House
{
// реализация    
}

class Factory
{
    public function factoryMethod($color)
    {
        switch($color)
        {
            case 'Red':
                return new RedHouse();
                
            case 'Blue':
                return new BlueHouse();

            default :
                throw new Exception('Undefined house\'s color');
        }
    }
}

Is it possible to use Switch/Case to create objects?
So far, I haven’t found anything against it, but I haven’t found that it’s 100% mandatory either. Who can refute?
Please respond only to those who are familiar with this pattern!!

Answer the question

In order to leave comments, you need to log in

2 answer(s)
E
Evgeny Bukharev, 2016-08-08
@evgenybuckharev

class BlueHouse extends House{}

class RedHouse extends House{}

abstract class House
{
    const RED= 1;
    const BLUE= 2;

    public static function getInstance($color)
    {
        switch($color)
        {
            case self::RED:
                return new RedHouse();
                break;
            case self::BLUE:
                return new BlueHouse();
                break;
            default :
                throw new Exception('Undefined house\'s color');
                break;
        }
    }

    abstract function build();
    abstract function demolition();
}

F
Finsh, 2016-10-29
@Finsh

reflectionclass somehow used reflection for this purpose

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question