-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathAbstractFactory.php
More file actions
133 lines (115 loc) · 2.71 KB
/
AbstractFactory.php
File metadata and controls
133 lines (115 loc) · 2.71 KB
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
<?php
/**
* 抽象工厂模式
* 提供一个创建一系列相关或相互依赖对象的接口,而无需指定它们具体的类
*/
/**
* 定义我需要插入和获取数据的接口
*/
interface IDepartment
{
public function insert(Department $department);
public function getDepartment($id);
}
/**
* Class MySqlDepartment
* 这是MySql的一种实现
*/
class MySqlDepartment implements IDepartment
{
public function insert(Department $department)
{
echo 'mysql 新增记录' . PHP_EOL;
}
public function getDepartment($id)
{
echo 'mysql 查询一条记录' . PHP_EOL;
}
}
/**
* Class SqlServerDepartment
* 这是SqlServer的实现
*/
class SqlServerDepartment implements IDepartment
{
public function insert(Department $department)
{
echo 'sqlServer 新增记录' . PHP_EOL;
}
public function getDepartment($id)
{
echo 'sqlServer 查询一条记录' . PHP_EOL;
}
}
/**
* 工厂接口,定义了创建驱动的接口
*/
interface InterfaceFactory
{
public function createDepartment();
}
class SqlServerFactory implements InterfaceFactory
{
public function createDepartment()
{
return new SqlServerDepartment();
}
}
class MySqlFactory implements InterfaceFactory
{
public function createDepartment()
{
return new MySqlDepartment();
}
}
class Department
{
}
$department = new Department();
$iDepartment = (new MySqlFactory())->createDepartment();
$iDepartment->insert($department);
$iDepartment->getDepartment(1);
$iDepartment = (new SqlServerFactory())->createDepartment();
$iDepartment->insert($department);
$iDepartment->getDepartment(1);
/**
* Class DepartmentManager
* 在各个框架实现,一般会定义一个类来管理这些驱动
*/
class DepartmentManager
{
/**
* @var string
*/
private $drive;
/**
* DepartmentManager constructor.
* @param string|null $drive
*/
public function __construct(string $drive = null)
{
$this->drive = $drive;
}
/**
* @return IDepartment
*/
public function createDepartment(): IDepartment
{
// 只是简单的使用switch来示例
switch ($this->drive) {
case 'sqlserv':
$iDepartment = new SqlServerFactory();
break;
case 'mysql':
default:
$iDepartment = new MySqlFactory();
break;
}
return $iDepartment->createDepartment();
}
}
// 使用的时候可以根据我们指定的配置实例化指定的驱动,然后使用
$manager = new DepartmentManager();
$dep = $manager->createDepartment();
$dep->insert($department);
$dep->getDepartment(1);