Design Patterns PHP - Flyweight Java

1) What have we done?

First of all we created interface "Flyweight" with a setter for injecting "different" parameter.
Our "Service" class just implements an interface "Flyweight"


class Service implements Flyweight
{
    /**
     * @var string
     */
    protected $same;

    /**
     * @var string
     */
    protected $different;

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

    public function doSomething()
    {
        echo sprintf('doing something with parameters %s %s ', $this->same, $this->different) . PHP_EOL;
    }

    /**
     * @param string $different
     */
    public function setDifferent($different)
    {
        $this->different = $different;
    }
}

interface Flyweight
{
    /**
     * @param string $different
     */
    public function setDifferent($different);
}




2) FlyweightFactory what is this?

Ok we have objects "Flyweights" which by default only has set "same" parameter.
We want to manage these objects and provide them to client. This is responsibility of "FlyweightFactory"

"FlyweightFactory" define method "getService".


class FlyweightFactory
{
    /**
     * @var Flyweight[]
     */
    protected $flyweights;

    /**
     * @param string $same
     * @return Flyweight
     */
    public function getService($same)
    {
        if (!isset($this->flyweights[$same])) {
            $this->flyweights[$same] = new Service($same);
        }

        return $this->flyweights[$same];
    }
}




3) How does usage look now?

In client we can see that now we don't create object "Service" every time instead of this we get it from "FlyweightFactory" which stores objects with different
"same" parameters.


for ($i = 0; $i < 10; $i++) {
    $service = $factory->getService('aaaa');
    $service->setDifferent(uniqid());
    $service->doSomething();
}

for ($i = 0; $i < 10; $i++) {
    $service = $factory->getService('bbbb');
    $service->setExtrinsic(uniqid());
    $service->doSomething();
}




Before every invoking of method "doSomething" we need to take care to inject state of "different" parameter

Let's notice than now we created only two instances of "Service" instead of 20 in step one. But the functionality is the same.