本篇文章是学习PHP中常用的三种设计模式的笔记及总结,不管采用哪一门语言开发什么,几乎都会使用到设计模式,我们为什么需要设计模式呢?它的诞生对于我们开发人员来说有什么样的作用与意义呢?
相信做iOS开发的人员对设计模式也会挺熟悉吧?比如单例设计模式、工厂设计模式、观察者模式、MVC框架结构设计模式等。
接下来我们一起来学习PHP中最常用的三种设计模式:单例设计模式、工厂设计模式和观察者设计模式。
单例设计模式
所谓单例模式,即在应用程序中最多只有该类的一个实例存在,一旦创建,就会一直存在于内存中!
单例设计模式常应用于数据库类设计,采用单例模式,只连接一次数据库,防止打开多个数据库连接。
一个单例类应具备以下特点:
单例类不能直接实例化创建,而是只能由类本身实例化。因此,要获得这样的限制效果,构造函数必须标记为private,从而防止类被实例化。
需要一个私有静态成员变量来保存类实例和公开一个能访问到实例的公开静态方法。
在PHP中,为了防止他人对单例类实例克隆,通常还为其提供一个空的私有__clone()方法。
单例模式的例子:
<?php
/**
* Singleton of Database
*/
class Database
{
// We need a static private variable to store a Database instance.
privatestatic $instance;
// Mark as private to prevent it from being instanced.
privatefunction__construct()
{
// Do nothing.
}
privatefunction__clone()
{
// Do nothing.
}
publicstatic functiongetInstance()
{
if (!(self::$instanceinstanceofself)) {
self::$instance = newself();
}
returnself::$instance;
}
}
$a =Database::getInstance();
$b =Database::getInstance();
// true
var_dump($a === $b);
工厂设计模式
工厂设计模式常用于根据输入参数的不同或者应用程序配置的不同来创建一种专门用来实例化并返回其对应的类的实例。
我们举例子,假设矩形、圆都有同样的一个方法,那么我们用基类提供的API来创建实例时,通过传参数来自动创建对应的类的实例,他们都有获取周长和面积的功能。
<?php
interfaceInterfaceShape
{
functiongetArea();
functiongetCircumference();
}
/**
* 矩形
*/
class Rectangle implementsInterfaceShape
{
private $width;
private $height;
publicfunction__construct($width, $height)
{
$this->width = $width;
$this->height = $height;
}
publicfunctiongetArea()
{
return $this->width* $this->height;
}
publicfunctiongetCircumference()
{
return 2 * $this->width + 2 * $this->height;
}
}
/**
* 圆形
*/
class Circle implementsInterfaceShape
{
private $radius;
function__construct($radius)
{
$this->radius = $radius;
}
publicfunctiongetArea()
{
return M_PI * pow($this->radius, 2);
}
publicfunctiongetCircumference()
{
return 2 * M_PI * $this->radius;
}
}
/**
* 形状工厂类
*/
class FactoryShape
{
publicstatic functioncreate()
{
switch (func_num_args()) {
case1:
return newCircle(func_get_arg(0));
case2:
return newRectangle(func_get_arg(0), func_get_arg(1));
default:
# code...
break;
}
}
}
$rect =FactoryShape::create(5, 5);
// object(Rectangle)#1 (2) { ["width":"Rectangle":private]=> int(5) ["height":"Rectangle":private]=> int(5) }
var_dump($rect);
echo "<br>";
// object(Circle)#2 (1) { ["radius":"Circle":private]=> int(4) }
$circle =FactoryShape::create(4);
var_dump($circle);







