延迟初始化与单例模式

Java 代码优化

Pavlos Kosmetatos

Lead Engineer @Wealthyhood

构建 Redis 缓存客户端

  • 设想我们在构建一个访问 Redis 的缓存客户端
  • 我们的 Redis 客户端托管在第三方服务商
  • 建立连接需要一次网络调用——假设耗时 500ms

$$

通过网络建立 Redis 连接的调用

Java 代码优化

一个简单(急切)的实现

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");
    }
}
  • 在构造函数中急切初始化 Redis 连接
Java 代码优化

该方法的潜在问题

看起来简单且可用,但存在潜在问题

如果我们根本不需要 Redis 客户端呢?

  • 启动时白白耗时
  • 建立了不必要的连接
Java 代码优化

延迟初始化

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 代码优化

单例模式

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 代码优化

Passons à la pratique !

Java 代码优化

Preparing Video For Download...