PHP设计模式—享元模式

定义:

享元模式(Flyweight):运用共享技术有效地支持大量细粒度的对象。

结构:

  • Flyweight:享元抽象类,所有具体享元类的接口,通过这个接口,Flyweight 可以接受并作用于外部状态。
  • ConcreteFlyweight:实现 Flyweight 接口的可以共享的具体享元类。
  • UnsharedConcreteFlyweight:非共享的具体享元类。
  • FlyweightFactory:享元工厂,用来创建并管理 Flyweight 对象,它主要是用来确保合理地共享 Flyweight,当用户请求一个 Flyweight 时,FlyweightFactory 对象提供一个已创建的实例或者创建一个(如果不存在的话)。
  • Client:客户端代码。

代码实例:

/**
 * 抽象类
 * Class Flyweight
 */
abstract class Flyweight
{
    protected $name;

    public function __construct($name)
    {
        $this->name = $name;
    }

    abstract public function show($content);
}

/**
 * 共享的具体类
 * Class ConcreteFlyweight
 */
class ConcreteFlyweight extends Flyweight
{

    /**
     * @param $content
     */
    public function show($content)
    {
        // TODO: Implement show() method.

        echo "共享的享元:{$this->name} {$content} ";
    }

}

/**
 * 不共享的具体类
 * Class UnsharedConcreteFlyweight
 */
class UnsharedConcreteFlyweight extends Flyweight
{

    /**
     * @param $content
     */
    public function show($content)
    {
        // TODO: Implement show() method.

        echo "不共享的享元:{$this->name} {$content} ";
    }

}

/**
 * 享元工厂
 * Class FlyweightFactory
 */
class FlyweightFactory
{

    /**
     * @var array
     */
    private $flyweights = [];

    /**
     * @param $name
     * @return mixed
     */
    public function getFlyweight($name)
    {
        if (!isset($this->flyweights[$name])) {
            $this->flyweights[$name] = new ConcreteFlyweight($name);
        }
        return $this->flyweights[$name];
    }

}

##客户端代码
// 创建享元工厂
$flyweightFactory = new FlyweightFactory();

// 共享的享元
$flyweight = $flyweightFactory->getFlyweight('state A');
$flyweight->show('other state A');
$flyweight = $flyweightFactory->getFlyweight('state B');
$flyweight->show('other state B');

// 不共享的对象,单独调用
$uflyweight = new UnsharedConcreteFlyweight('state A');
$uflyweight->show('state A');

##测试结果
共享的享元:state A other state A
共享的享元:state B other state B
不共享的享元:state A state A

总结:

  • 享元模式的目的是为了减少实例化大量的类时对内存的占用。
  • 如果一个应用程序使用了大量的对象,而大量的这些对象造成了很大的存储开销时就应该考虑使用;还有就是对象的大多数状态可以外部状态,如果删除对象的外部状态,那么可以用相对较少的共享对象取代很多组对象,此时可以考虑使用享元模式。

Original: https://www.cnblogs.com/woods1815/p/16183117.html
Author: 幽篁晓筑
Title: PHP设计模式—享元模式

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/581914/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

亲爱的 Coder【最近整理,可免费获取】👉 最新必读书单  | 👏 面试题下载  | 🌎 免费的AI知识星球