Answer the question
In order to leave comments, you need to log in
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');
}
}
}
Answer the question
In order to leave comments, you need to log in
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();
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question