Optimasi Kode di Java
Pavlos Kosmetatos
Lead Engineer @Wealthyhood
$$

public class RedisCache {
// Library klien untuk terhubung ke Redis
private final RedisClient client;
public RedisCache() {
// Koneksi disiapkan di dalam konstruktor
connection = new RedisClient("cache.mycompany.com");
}
}
Ini tampak sederhana—dan akan berfungsi—tetapi berpotensi bermasalah
Bagaimana jika kita tidak butuh klien Redis sama sekali?
public class RedisCache {
private RedisClient client;
// Alih-alih menyiapkan koneksi di konstruktor,
// kita menyiapkannya hanya saat klien dibutuhkan.
public RedisClient getClient() {
if (connection == null) {
connection = new RedisClient("cache.mycompany.com");
}
return connection;
}
}
// UserService membutuhkan akses cache
public class UserService {
private RedisCache userCache = new RedisCache(); // Koneksi pertama
}
// PaymentService juga butuh cache
public class PaymentService {
private RedisCache paymentCache = new RedisCache(); // Koneksi kedua
}
// ...begitu juga OrderService ...
public class RedisCache {
private static RedisCache instance;
private RedisClient client;
// Konstruktor private agar RedisCache hanya dibuat
// di dalam kelas ini
private RedisCache() {}
public static RedisCache getInstance()
// Buat RedisCache hanya jika belum ada
if (instance == null) { instance = new RedisCache(); }
return instance;
}
// ... Sisanya sama seperti sebelumnya ...
}
Optimasi Kode di Java