jeudi 27 février 2020

How to implement proxy pattern?

I'm trying to understand how to make and use a proxy design pattern. I have no idea what am i doing wrong. Any suggestions would be appreciated:

Load method should simulate downloading configuration from remote server... and it kinda does. The 2 seconds delay should be launched just once, and then it should go smoothly.

public interface ConfigLoader {

     String load();
}

RealObject

import lombok.Getter;
import lombok.Setter;
import org.apache.commons.lang3.RandomStringUtils;
import pl.sdacademy.prog.streams.MyExepction;

@Getter
@Setter
public class ConfigLoaderImplementation implements ConfigLoader {
    private String configuration;
    private String serverUrl;

    public ConfigLoaderImplementation(final String serverUrl) {
        this.serverUrl = serverUrl;
    }

    @Override
    public String load() {
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            throw new MyException("Sleeping canceled!", e);
        }
        System.out.println("Configuration from " + getServerUrl() + " downloaded successfully");
        String generatedConfiguration = RandomStringUtils.randomAlphabetic(10);
        setConfiguration(generatedConfiguration);
        return generatedConfiguration;
    }
}

Proxy

import lombok.Data;

@Data

public class ConfigLoaderProxy implements ConfigLoader {

    private ConfigLoader proxy;

    public ConfigLoaderProxy(String url) {
        this.proxy = proxy;
    }

    @Override
    public String load() {
        if (proxy == null) {
            proxy = new ConfigLoaderImplementation("www.blablA.com");
            return proxy.load();

        } else {
            return proxy.load();
        }
        //todo

    }
}

Test class, with main

public class ConfigLoaderDemo {
    public static void main(String[] args) {

        ConfigLoader proxy = new ConfigLoaderProxy("sdasd");

        proxy.load();
        proxy.load();
        proxy.load();
    }
}

Aucun commentaire:

Enregistrer un commentaire