Lazy initialization และ Singleton Pattern

การปรับแต่งโค้ดใน Java

Pavlos Kosmetatos

Lead Engineer @Wealthyhood

สร้าง Redis Cache Client

  • สมมติว่ากำลังสร้าง Cache Client ที่เชื่อมต่อกับ Redis
  • Redis Client ของเราโฮสต์อยู่กับผู้ให้บริการภายนอก
  • การเชื่อมต่อต้องใช้การเรียกผ่านเครือข่าย — สมมติว่าใช้เวลา 500ms

$$

การเรียกผ่านเครือข่ายเพื่อสร้างการเชื่อมต่อ Redis

การปรับแต่งโค้ดใน Java

การ Implement แบบง่าย (Eager)

public class RedisCache {
    // The client library we use to connect to Redis
    private final RedisClient client;

    public RedisCache() {
        // The connection is setup inside the constructor
        connection = new RedisClient("cache.mycompany.com");
    }
}
  • Eager initialization ของการเชื่อมต่อ Redis
การปรับแต่งโค้ดใน Java

ปัญหาที่อาจเกิดขึ้นกับแนวทางนี้

This seems simple - and would work - but it has a potential issue

What if we don't need the Redis client at all?

  • We wasted precious time at startup
  • We established unnecessary connections
การปรับแต่งโค้ดใน Java

Lazy Initialization

public class RedisCache {
    private RedisClient client;

    // Instead of setting up the connection in the constructor,
    // we only set it up when someone needs to get the client.
    public RedisClient getClient() {
        if (connection == null) {
            connection = new RedisClient("cache.mycompany.com");
        }
        return connection;
    }
}
การปรับแต่งโค้ดใน Java

ปัญหาอีกอย่างของแนวทางนี้

// UserService needs cache access
public class UserService {
    private RedisCache userCache = new RedisCache();  // First connection
}

// PaymentService also needs cache
public class PaymentService {
    private RedisCache paymentCache = new RedisCache();  // Second connection
}

// ...same for OrderService ...
การปรับแต่งโค้ดใน Java

Singleton Pattern

public class RedisCache {
    private static RedisCache instance;
    private RedisClient client;

    // The constructor is private so that we ensure we only
    // create RedisCache inside this class
    private RedisCache() {}

    public static RedisCache getInstance() 
        // We only create a RedisCache if one does not already exist
        if (instance == null) { instance = new RedisCache(); }
        return instance;
    }

    // ... The rest is the same as before ...
}
การปรับแต่งโค้ดใน Java

มาฝึกกันเถอะ!

การปรับแต่งโค้ดใน Java

Preparing Video For Download...