“设计模式之工厂模式 抽象工厂”

设计模式之工厂模式 抽象工厂

多个类具有相同的属性和方法

1.首先声明类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Mysql
{

}

class Sqlite
{

}

class MyPdo
{

}

2.建立一个工厂类接口,工厂类中可以声明属性和方法

1
2
3
4
5
interface Factory {

public static function getDB();

}

3.然后声明抽象工厂类 实现工厂类接口中的静态方法

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
class MysqlFactory implements Factory
{
public static function getDB() {
return new Mysql();
}
}

class MyPdoFactory implements Factory
{
public static function getDB()
{
// TODO: Implement getDB() method.
return new MyPdo();
}
}

class MysqlliteFactory implements Factory
{
public static function getDB()
{
// TODO: Implement getDB() method.
return new Sqlite();
}
}

4、最后调用工厂类中的静态方法

1
2
3
$factory = 'MysqlFactory';
$db = $factory::getDB();
print_r($db);