-
Notifications
You must be signed in to change notification settings - Fork 0
/
SimpleFactory.php
49 lines (43 loc) · 934 Bytes
/
SimpleFactory.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
<?php
/**
* 简单/静态工厂
*/
require_once __DIR__ . "/Animal.php";
class AnimalFactory
{
/**
* 制造动物
*
* @param string $type 动物类型
*
* @return Animal
*/
public static function make(string $type): Animal
{
switch ($type) {
case "Cat":
case "cat":
return new Cat;
break;
case "Dog":
case "dog":
return new Dog;
break;
default:
return new $type;
}
}
}
$cat = AnimalFactory::make('cat');
$dog = AnimalFactory::make('dog');
var_dump($cat, $dog);
// F:\Code\code\design-pattern\Factory\SimpleFactory.php:49:
// class Cat#1 (1) {
// public $name =>
// string(3) "Cat"
// }
// F:\Code\code\design-pattern\Factory\SimpleFactory.php:49:
// class Dog#2 (1) {
// public $name =>
// string(3) "Dog"
// }