PHP7 Static Factory

This commit is contained in:
Dominik Liebler
2016-09-22 13:03:03 +02:00
parent ce1b53847d
commit e675a5f0ac
2 changed files with 24 additions and 32 deletions

View File

@@ -3,30 +3,26 @@
namespace DesignPatterns\Creational\StaticFactory;
/**
* Note1: Remember, static => global => evil
* Note1: Remember, static means global state which is evil because it can't be mocked for tests
* Note2: Cannot be subclassed or mock-upped or have multiple different instances.
*/
class StaticFactory
final class StaticFactory
{
/**
* the parametrized function to get create an instance.
*
* @param string $type
*
* @static
*
* @throws \InvalidArgumentException
*
* @return FormatterInterface
*/
public static function factory($type)
public static function factory(string $type): FormatterInterface
{
$className = __NAMESPACE__.'\Format'.ucfirst($type);
if (!class_exists($className)) {
throw new \InvalidArgumentException('Missing format class.');
if ($type == 'number') {
return new FormatNumber();
}
return new $className();
if ($type == 'string') {
return new FormatString();
}
throw new \InvalidArgumentException('Unknown format given');
}
}