import java.util.HashMap;
import java.util.Map;
/**
* {@link <a href=
* "https://[Log in to view URL]"
* target= "_blank"></a>}
*
* @author itammb ( Italia Massimiliano Buscati )
* @version JDK 1.15
*
*/
class Main {
public interface ServiceInterface {
String getUserData(String userId);
}
public static class UserServiceProxy implements ServiceInterface {
private final ServiceInterface realUserService;
private final Map<String, String> cache = new HashMap<>();
public UserServiceProxy(ServiceInterface realUserService) {
this.realUserService = realUserService;
}
@Override
public String getUserData(String userId) {
// query logica
if (cache.containsKey(userId)) {
System.out.println("Retrieved from cache: " + userId);
return cache.get(userId);
}
// query fisica
String data = realUserService.getUserData(userId);
cache.put(userId, data);
System.out.println("Fetched from database and cached: " + userId);
return data;
}
}
public static class RealUserService implements ServiceInterface {
@Override
public String getUserData(String userId) {
// Simulate a slow database query
try {
Thread.sleep(2000);
// 2-second delay } catch
} catch (InterruptedException e) {
e.printStackTrace();
}
return "Data for user: " + userId;
}
}
public static void main(String args[]) {
// Unit test - uso del design pattern: proxy
ServiceInterface realUserService = new RealUserService();
ServiceInterface proxy = new UserServiceProxy(realUserService);
System.out.println(proxy.getUserData("user1")); // dalla cache
System.out.println(proxy.getUserData("user2")); // dal database
System.out.println(proxy.getUserData("user2")); // dalla cache
}
}
To embed this project on your website, copy the following code and paste it into your website's HTML: