简单工厂模式

工厂模式也是创建型模式,常说的工厂模式主要包含三种,简单工厂模式,工厂模式,抽象工厂模式,三种可以理解为一个逐步抽象的过程。
后续分别会对三种工厂模式分别做简单介绍,本文首先介绍简单工厂模式

意图

适用性

结构

simple_factory
从图上可以看出,简单工厂模式主要有三个元素,1、client(调用工厂);2、简单工厂类(生成者);3、产品类
其中简单工厂类根据client传入的产品需求来生产。所有的产品类都有统一的特征,每个具体的产品都是是产品接口实现

代码示例

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
//工厂类
class fruitFactory
{
public static function createFruit($fruitName)
{
$className = ucfirst($fruitName);
if(class_exists($className))
{
return new $className;
}
else
{
throw new Exception('we can not create fruit [' . $fruitName . ']');
}
}
}
//产品类
interface Fruit
{
public function getFruit();
}
class Apple implements Fruit
{
public function getFruit()
{
echo 'I am Apple' . PHP_EOL;
}
}
class Pear implements Fruit
{
public function getFruit()
{
echo 'I am Pear' . PHP_EOL;
}
}
class Banana implements Fruit
{
public function getFruit()
{
echo 'I am Banana' . PHP_EOL;
}
}
//client
$fruitName = isset($argv[1]) ? $argv[1] : "";
try
{
if(empty($fruitName))
{
throw new Exception("must choose fruit");
}
$fruit = fruitFactory::createFruit($fruitName);
$fruit->getFruit();
}
catch(Exception $e)
{
echo $e->getMessage() . PHP_EOL;
}

明显特征

  1. 通过客户端输入参数给工厂来创建产品
  2. 每种产品都是一个抽象产品的实现(也可以是抽象类的继承)

参考文献

1.设计模式:简单工厂、工厂方法、抽象工厂之小结与区别
2.简单工厂模式