import java.util.HashMap; import java.util.Map; public class ProxyCacheDatabase implements Database { // Ο Proxy έχει ως πεδίο την πραγματική βάση private RealDatabase realDatabase; // Η μνήμη Cache για γρήγορη ανάκτηση private Map cache; public ProxyCacheDatabase() { this.realDatabase = new RealDatabase(); this.cache = new HashMap<>(); } @Override public String query(String sqlQuery) { System.out.println("[ProxyCache] Checking cache first..."); // 1. Αν το αποτέλεσμα υπάρχει στην Cache, το επιστρέφει ΚΑΤΕΥΘΕΙΑΝ if (cache.containsKey(sqlQuery)) { System.out.println("[ProxyCache] HIT! Found in Cache."); return cache.get(sqlQuery); } // 2. Αν ΔΕΝ υπάρχει στην Cache (Cache Miss) System.out.println("[ProxyCache] MISS! No data found in Cache. Connecting to RealDB..."); // Ρωτάει την πραγματική βάση String result = realDatabase.query(sqlQuery); // 3. Αποθηκεύει το νέο αποτέλεσμα στην Cache για το επόμενο request cache.put(sqlQuery, result); System.out.println("[ProxyCache] Updated cache."); return result; } }