Design Patterns Java - Flyweight Php

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"


public class Service implements Flyweight
{
    protected String same;

    protected String different;

    public Service(String same)
    {
        this.same = same;
    }

    @Override
    public void setDifferent(String different)
    {
        this.different = different;
    }

    public void doSomething()
    {
        System.out.printf("doing something with attributes %s %s\n", same, different);
    }
}

public interface Flyweight
{
    void setDifferent(String 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".


import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class FlyweightFactory
{
    protected Map<String, Service> flyweightList = new ConcurrentHashMap<>();

    public Service getService(String same)
    {
        if (!flyweightList.containsKey(same))
        {
            flyweightList.put(same, new Service(same));
        }

        return flyweightList.get(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.


import java.util.UUID;
import java.util.stream.Stream;

public class Client
{
    public static void main(String[] args)
    {
        FlyweightFactory factory = new FlyweightFactory();

        Stream.generate(() -> {
            return factory.getService("aaaaaa");
        }).peek((s) -> s.setDifferent(UUID.randomUUID().toString())).limit(10).forEach(Service::doSomething);

        Stream.generate(() -> {
            return factory.getService("bbbbbb");
        }).peek((s) -> s.setDifferent(UUID.randomUUID().toString())).limit(10).forEach(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.