gpt4 book ai didi

java - 如何实现代理模式?

转载 作者:太空宇宙 更新时间:2023-11-04 09:04:10 24 4
gpt4 key购买 nike

我试图了解如何制作和使用代理设计模式。我不知道我做错了什么。任何建议将不胜感激:

加载方法应该模拟从远程服务器下载配置......而且确实如此。 2 秒的延迟应该只启动一次,然后就应该顺利进行。

public interface ConfigLoader {

String load();
}

真实对象

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;
}
}

代理

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

}
}

测试类,主要

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

ConfigLoader proxy = new ConfigLoaderProxy("sdasd");

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

最佳答案

public class ConfigLoaderProxy implements ConfigLoader {

private final ConfigLoader configLoader;
private String configuration;

public ConfigLoaderProxy(final ConfigLoader configLoader) {
this.configLoader = configLoader;
}

@Override
public String load() {
if (configuration == null) {
configuration = configLoader.load();
}
return configuration;
}
}

关于java - 如何实现代理模式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60432216/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com