Guava Supplier實例

今天想講一下Guava Suppliers的幾點用法。Guava Suppliers的主要功能是建立包裹的單例對象,經過get方法能夠獲取對象的值。每次獲取的對象都爲同一個對象,但你和單例模式有所區別,Suppliers具有更加迷人的色彩。本文會經過幾個實例來說解Guava Suppliers的一些特性。
數據庫

Code Test Case

Lazy初始化,Supplier wrapped的對象只在第一次get時候會被初始化

@Test
    public void should_init_the_supplier_wrapped_object_when_get_object() 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("main thread block");
        Thread.sleep(2000);
        System.out.println(memoize.get());
    }

Supplier wrapped對象只初始化一次

@Test
    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());
    }

能夠使用memoizeWithExpiration函數建立過時設置的Supplier對象,時間過時,get對象會從新初始化對象

@Test
    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());
    }

Conclsion

Suppliers的特性能夠用來對程序中只須要初始化一次的資源進行管理,好比數據庫管理對象,固然,用戶也能夠根據需求選擇是否須要定時更新對象,總而言之,Suppliers給咱們編程帶來了更多的選擇。編程

今天是國慶節,祝願你們國慶七天樂,玩的開心:)app

相關文章
相關標籤/搜索