File tree 2 files changed +20
-28
lines changed
2 files changed +20
-28
lines changed Original file line number Diff line number Diff line change 3
3
namespace DesignPatterns \Creational \StaticFactory ;
4
4
5
5
/**
6
- * Note1: Remember, static => global => evil
6
+ * Note1: Remember, static means global state which is evil because it can't be mocked for tests
7
7
* Note2: Cannot be subclassed or mock-upped or have multiple different instances.
8
8
*/
9
- class StaticFactory
9
+ final class StaticFactory
10
10
{
11
11
/**
12
- * the parametrized function to get create an instance.
13
- *
14
12
* @param string $type
15
13
*
16
- * @static
17
- *
18
- * @throws \InvalidArgumentException
19
- *
20
14
* @return FormatterInterface
21
15
*/
22
- public static function factory ($ type )
16
+ public static function factory (string $ type ): FormatterInterface
23
17
{
24
- $ className = __NAMESPACE__ .'\Format ' .ucfirst ($ type );
18
+ if ($ type == 'number ' ) {
19
+ return new FormatNumber ();
20
+ }
25
21
26
- if (! class_exists ( $ className ) ) {
27
- throw new \ InvalidArgumentException ( ' Missing format class. ' );
22
+ if ($ type == ' string ' ) {
23
+ return new FormatString ( );
28
24
}
29
25
30
- return new $ className ( );
26
+ throw new \ InvalidArgumentException ( ' Unknown format given ' );
31
27
}
32
28
}
Original file line number Diff line number Diff line change 4
4
5
5
use DesignPatterns \Creational \StaticFactory \StaticFactory ;
6
6
7
- /**
8
- * Tests for Static Factory pattern.
9
- */
10
7
class StaticFactoryTest extends \PHPUnit_Framework_TestCase
11
8
{
12
- public function getTypeList ()
9
+ public function testCanCreateNumberFormatter ()
13
10
{
14
- return array (
15
- array ( ' string ' ) ,
16
- array ('number ' ),
11
+ $ this -> assertInstanceOf (
12
+ ' DesignPatterns\Creational\StaticFactory\FormatNumber ' ,
13
+ StaticFactory:: factory ('number ' )
17
14
);
18
15
}
19
16
20
- /**
21
- * @dataProvider getTypeList
22
- */
23
- public function testCreation ($ type )
17
+ public function testCanCreateStringFormatter ()
24
18
{
25
- $ obj = StaticFactory::factory ($ type );
26
- $ this ->assertInstanceOf ('DesignPatterns\Creational\StaticFactory\FormatterInterface ' , $ obj );
19
+ $ this ->assertInstanceOf (
20
+ 'DesignPatterns\Creational\StaticFactory\FormatString ' ,
21
+ StaticFactory::factory ('string ' )
22
+ );
27
23
}
28
24
29
25
/**
30
- * @expectedException InvalidArgumentException
26
+ * @expectedException \ InvalidArgumentException
31
27
*/
32
28
public function testException ()
33
29
{
34
- StaticFactory::factory ('' );
30
+ StaticFactory::factory ('object ' );
35
31
}
36
32
}
You can’t perform that action at this time.
0 commit comments