php 设计模式之 享元



1. 享元模式

享元模式使用共享物件,减少运行时对象实例的个数,节省内存

将许多“虚拟”对象的状态集中管理,

一旦被实现,单个的逻辑实现将无法拥有独立而不同的行为

当一个类有许多的实例,而这些实例能被同一方法控制,就可以使用享元模式


2. 实列

interface Flyweight
{
    public function operation($extrinsicState) : void;
}

class ConcreteFlyweight implements Flyweight
{
    private $intrinsicState = 101;
    function operation($extrinsicState) : void
    {
        echo '共享享元对象' . ($extrinsicState + $this->intrinsicState) . PHP_EOL;
    }
}

class UnsharedConcreteFlyweight implements Flyweight
{
    private $allState = 1000;
    public function operation($extrinsicState) : void
    {
        echo '非共享享元对象:' . ($extrinsicState + $this->allState) . PHP_EOL;
    }
}

class FlyweightFactory
{
    private $flyweights = [];

    public function getFlyweight($key) : Flyweight
    {
        if (!array_key_exists($key, $this->flyweights)) {
            $this->flyweights[$key] = new ConcreteFlyweight();
        }
        return $this->flyweights[$key];
    }
}

$factory = new FlyweightFactory();

$extrinsicState = 100;
$flA = $factory->getFlyweight('a');
$flA->operation(--$extrinsicState);

$flB = $factory->getFlyweight('b');
$flB->operation(--$extrinsicState);

$flC = $factory->getFlyweight('c');
$flC->operation(--$extrinsicState);

$flD = new UnsharedConcreteFlyweight();
$flD->operation(--$extrinsicState);


3. 使用场景

  1. 围棋棋盘有黑白两色,实例两个对象
posted @ 2020-12-30 18:49  linsonga  阅读(68)  评论(0)    收藏  举报