2.2. 抽象工厂模式(Abstract Factory)
定义 (部分)
- 通常创建的类都实现相同的接口
- 抽象工厂的客户并不关心这些对象是如何创建的
 来自:PHP 设计模式全集 - 抽象工厂模式(Abstract...
uml

不应该 new FileCache()应该 (new CacheFactory())->getFileCache()
代码实现
CacheAbstractFactoryInterface.php
<?php
namespace App\AbstractFactory;
interface CacheAbstractFactoryInterface
{
  public function put($key,$str);
  public function get($str);
}FileCache.php
<?php
namespace App\AbstractFactory;
class FileCache implements CacheAbstractFactoryInterface
{
    public function put($key,$str)
    {
        return "file cache write string ".$str;
    }
    public function get($key)
    {
        return "file cache get key ".$key;
    }
}    RedisCache.php
<?php
namespace App\AbstractFactory;
class RedisCache implements CacheAbstractFactoryInterface
{
  public function put($key,$str)
 {  return "redis cache write string ".$str;
 }
  public function get($key)
  {  return "redis cache get key ".$key;
  }
}CacheFactory.php
<?php
namespace App\AbstractFactory;
class CacheFactory
{
    public function getFileCache()
    {
        return  new FileCache();
    }
    public function getRedisCache()
    {
        return new RedisCache();
    }
}好处 [管理方便]
- 比如想把getFileCache()变成单例。
protected $fileCache;
public function getFileCache()
{
  if($fileCache != null)
  return $this->fileCache;
  return  $this->fileCache = new FileCache();
}- 服务器内存满了, 把redis换成filepublic function getRedisCache() { return new FileCache(); }
 
           php设计模式学习
php设计模式学习 
         
             
             关于 LearnKu
                关于 LearnKu
               
                     
                     
                     粤公网安备 44030502004330号
 粤公网安备 44030502004330号 
 
推荐文章: