转载:http://www.cnblogs.com/jun-ma/p/4850591.htmlhtml
Guava Suppliers的主要功能是建立包裹的单例对象,经过get方法能够获取对象的值。每次获取的对象都为同一个对象,但你和单例模式有所区别,Suppliers具有更加迷人的色彩。数据库
public void should_init_the_supplier_wrapped_object_when_get_object() throws Exception { 编程
Supplier<Integer> memoize = Suppliers.memoize(new Supplier<Integer>() { app
public Integer get() { 函数
System.out.println("init supplier wrapped object");spa
return 1;htm
}对象
}); blog
System.out.println("main thread block"); 资源
Thread.sleep(2000);
System.out.println(memoize.get());
}
public void should_init_the_supplier_wrapped_object_for_only_one_time() throws Exception {
Supplier<Integer> memoize = Suppliers.memoize(new Supplier<Integer>() {
public Integer get() {
System.out.println("init supplier wrapped object");
return 1;
}
});
System.out.println(memoize.get());
System.out.println(memoize.get());
}
public void should_re_init_the_supplier_wrapped_object_when_set_the_expire_time() throws Exception {
Supplier<Integer> memoize = Suppliers.memoizeWithExpiration(new Supplier<Integer>() {
public Integer get() { System.out.println("init supplier wrapped object");
return 1;
}
}, 5, TimeUnit.SECONDS);
System.out.println(memoize.get());
Thread.sleep(6000);
System.out.println(memoize.get());
}
总结:
Suppliers的特性能够用来对程序中只须要初始化一次的资源进行管理,好比数据库管理对象,固然,用户也能够根据需求选择是否须要定时更新对象,总而言之,
Suppliers给咱们编程带来了更多的选择。