Design Patterns Java - Proxy Php

1) What have we at the beginning?

We have object "Subject" which has method "doSomething"

public class Subject
{
    public Subject()
    {
        try
        {
            Thread.sleep(10);
        } catch (InterruptedException e)
        {
            e.printStackTrace();
        }
    }

    public void doSomething()
    {
        System.out.println("doing something");
    }
}



Let's assume that creating this types of objects is heavy. In our case it's time-consuming.
We add sleep for 0.1 of second in the constructor

2) How looks the client?

import java.util.ArrayList;
import java.util.List;
import java.util.stream.IntStream;
import java.util.stream.Stream;

public class Client
{
    public static void main(String[] args)
    {
        List<Subject> subjects = new ArrayList<>();
        Stream.generate(Subject::new).limit(500).forEach(subjects::add);

        //some code

        subjects.stream().limit(10).forEach(Subject::doSomething);
    }
}



Let's imagine that we need a pool of 500 objects.

Later in some other places we use for example 10 objects.

3) What are disadvantages?

Unfortunately if we want run this code we need to wait for 5 second before we can use this pool of objects.

4) How we can solve this?

Let's apply "Proxy" pattern