Design Patterns PHP - Flyweight Java

1) What have we at the beginning?

We have class "Service" with two attributes:

- same
- different


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

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

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

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




"Service" responsibility is to provide implementation of method "doSomething"

2) Assumptions?

Let's assume that attribute: "same" often repeats but "different" often is different

3) Let's see this on client side

We create "Service" 20 times and next we invoke desirable method "doSomething"


for ($i = 0; $i < 10; $i++) {
    $service = new Service('aaaaa', uniqid());
    $service->doSomething();
}

for ($i = 0; $i < 10; $i++) {
    $service = new Service('bbbb', uniqid());
    $service->doSomething();
}




4) Can we do this better?

Yes, we don't have to keep param "wide" in "Service" we can inject it when we would like to call "doSomething" method