Design Patterns Java - Flyweight Php

1) What have we at the beginning ?

We have class "Service" with two attributes:

- same
- different


public class Service
{
    protected String same;

    protected String different;

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

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




"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"


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

public class Client
{
    public static void main(String[] args)
    {
        Stream.generate(() -> {
            return new Service("aaaaaa", UUID.randomUUID().toString());
        }).limit(10).forEach(Service::doSomething);

        Stream.generate(() -> {
            return new Service("bbbbbb", UUID.randomUUID().toString());
        }).limit(10).forEach(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