一个简单的响应式用例
背景
今天在重构网络库初始化的时候,发现每次用户cookie变化,都会重新初始化网络库
究其原因,是因为网络库的网络拦截器需要用到用户cookie,用户cookie变化后,如果不重新初始化,就要导致网络拦截器的cookie还是上一次的,导致网络异常。
这种重复初始化网络库,感觉有点浪费了,所以我用响应式的思想,重构了一下代码
重构前,我们传给ClientInterceptor 的是一个具体的cookie值
重构后,我们传给ClientInterceptor 的是一个动态的lambda表达式,cookie的值由这个lambda表达式提供
由本例子,我们可以推而广之,我们的类会有各种状态,这些状态,有的是只由自己控制的,有的则是在外界变化时,需要一起变化的。
那么,对于那些可变状态,其实,我们完全可以传入一个lambda表达式,而不是一个具体的值,由此达到一处变化,处处变化
的目的。
好处
- 状态自动同步,防止自己管理状态,导致的状态不同步问题。
坏处
- 每一次需要该值,都会重复计算一次,当然,这也是为了保持它及时刷新不得不付出的代价
简化后的代码如下:
package com.daigou.sg.app;
/**
* author : yutianran
* time : 2019/05/07
* desc : 响应式用例
* version: 1.0
*/
public class ReactiveTestClient {
public static void main(String[] args) {
testNormal();
testReactive();
}
/**
* 传入的是一个具体的值
*/
private static void testNormal() {
Cache<String> cache = new Cache<>("en");
ClientInterceptor interceptor = new ClientInterceptor(cache.value);
System.out.println("testNormal:缓存变化前:" + interceptor.cookie);
cache.value = "zh";
System.out.println("testNormal:缓存变化后:" + interceptor.cookie);
}
/**
* 传入的是一个动态的表达式
*/
private static void testReactive() {
Cache<String> cache = new Cache<>("en");
ReactiveClientInterceptor interceptor = new ReactiveClientInterceptor(() -> cache .value);
System.out.println("testReactive:缓存变化前:" + interceptor.cookieProvider.provide());
holder.value = "zh";
System.out.println("testReactive:缓存变化后:" + interceptor.cookieProvider.provide());
}
static class Cache<T> {
T value;
public Cache(T value) {
this.value = value;
}
}
static class ReactiveClientInterceptor {
Provider<String> cookieProvider;
public ReactiveClientInterceptor(Provider<String> cookieProvider) {
this.cookieProvider = cookieProvider;
}
}
static class ClientInterceptor {
String cookie;
public ClientInterceptor(String cookie) {
this.cookie = cookie;
}
}
@FunctionalInterface
public interface Provider<T> {
T provide();
}
}