1. 程式人生 > 實用技巧 >php 設計模式之 享元

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. 圍棋棋盤有黑白兩色,例項兩個物件