PHP设计模式 - 工厂模式
工厂模式的实质是定义一个创建对象的公共类,让这个类中的方法来决定实例化哪个类。
假设现在项目里有一个生成图片验证码的类CaptchaClass.php,在一些类如注册、登录、发送手机验证码的场景中都用到了这个类。后来产品要求升级图片验证码,我们想保留原始文件,在一个新文件CaptchaNewClass.php里开始写新代码。完成后,意识到一个麻烦的问题,项目所有用到图片验证码的地方都需要更换新的类名。运用工厂方法则可以避免这种问题。
1 | class Factory |
在需要调用类的地方使用工厂方法来实例化类Factory::createCaptchaInstance(),替换的时候只需更改构造方法的注入类参数即可。
现在我们学会了单例和工厂两种设计模式,不妨结合起来使用一下。对上面的工厂类作如下修改:1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16class Factory
{
static $captchaInstance;
private function __construct(CaptchaNewClass $captcha)
{
self::$captchaInstance = $captcha;
}
static function createCaptchaInstance()
{
if (null === self::$captchaInstance) {
self::$captchaInstance = new self;
}
return self::$captchaInstance;
}
final private function __clone(){}
}