Design Patterns Java - Proxy Php

1) What have we done?

We just created "Subject" interface which define an functionality offered by this object.

Class "RealSubject" provide proper implementation. As we know creating of objects is time-consuming.

public interface Subject
{
    void doSomething();
}

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

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




2) What is the proxy?

"Proxy" is the special objects which is a "Subject" and has a "RealSubject" for offering the client the same implementation.
For the client "Proxy" is transparent as is a "Subject" type.


public class Proxy implements Subject
{
    protected Subject realSubject;

    @Override
    public void doSomething()
    {
        if (realSubject == null)
        {
            realSubject = new RealSubject();
        }

        realSubject.doSomething();
    }
}

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(Proxy::new).limit(500).forEach(subjects::add);

        //some code

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




In client now our pools is pools of "Proxy" objects not "RealSubject"
We just create "RealSubject" only when we need it.

Now we don't have to wait 5 seconds at the beginning and the functionality didn't change. Everything thanks to the "Proxy" objects.