2.2. 抽象工厂模式(Abstract Factory)

未匹配的标注

定义 (部分)

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

uml

抽象工厂模式(Abstract Factory)

不应该 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();
    }
}

好处 [管理方便]

  1. 比如想把getFileCache()变成单例。
protected $fileCache;
public function getFileCache()
{
  if($fileCache != null)
  return $this->fileCache;
  return  $this->fileCache = new FileCache();
}
  1. 服务器内存满了, 把redis换成file
    public function getRedisCache()
    {
    return new FileCache();
    }

本文章首发在 LearnKu.com 网站上。

上一篇 下一篇
讨论数量: 0
发起讨论 只看当前版本


暂无话题~