1. 程式人生 > >Guava學習筆記-Supplier

Guava學習筆記-Supplier

還是先貼程式碼,先跑起來再說^_^,都是抄書上的閉嘴

public class RegionPredicate implements Predicate<State> {
    @Override
    public boolean apply(State input) {
        return !Strings.isNullOrEmpty(input.getRegion())&&input.getRegion().equals("New York");
    }
}

class ComposedPredicateSupplier implements Supplier<Predicate<String>> {
    @Override
    public Predicate<String> get() {
        City city=new City("Austin,TX");
        State state=new State("Texas");
        state.setCode("TX");
        City city1=new City("New York,NY");
        State state1=new State("New York");
        state1.setCode("NY");
        Map<String,State> stateMap= Maps.newHashMap();
        stateMap.put(state.getCode(),state);
        stateMap.put(state1.getCode(),state1);
        Function<String,State> mf= Functions.forMap(stateMap);

        return Predicates.compose(new RegionPredicate(), mf);
    }
}

/**
 *
 * SupplierDemo介面
 * public interface Supplier<T>{
 *     T get();
 * }
 * get方法返回T的是一個例項,每次get呼叫可以返回相同的例項(單例)也可以每次返回新例項。
 * Supplier介面提供了一個靈活的延遲初始化機制直到get方法被呼叫。
 *
 * Supplier<T> Suppliers.memoize(Supplier<T> delegate)
 * 對delegate進行包裝,對其get呼叫將返回delegate.get的執行結果,只有第一次呼叫時delegate.get會被
 * 執行,Supplier<T>會快取delegate.get的結果,後面的呼叫將返回快取,即單例模式。
 *
 * Supplier<T> memoizeWithExpiration(Supplier<T> delegate, long duration, TimeUnit unit)
 * 功能與memoize相同,但是快取的結果具有時效性。
 */
public class SupplierDemo {

    @Test
    public void test(){
        ComposedPredicateSupplier composedPredicateSupplier=new ComposedPredicateSupplier();
        Predicate<String> predicate=composedPredicateSupplier.get();
        boolean isNy=predicate.apply("NY");
        System.out.println(isNy);

        Predicate<String> predicate1=composedPredicateSupplier.get();
        System.out.println(predicate==predicate1);

        Supplier<Predicate<String>> wrapped= Suppliers.memoize(composedPredicateSupplier);
        Predicate<String> predicate2=wrapped.get();
        Predicate<String> predicate3=wrapped.get();
        System.out.println(predicate2==predicate3);
    }
}
我想到的應用場景:
1.可以考慮使實體實現Supplier介面,用get作為其例項化方法

2.可以考慮Supplier介面和Suppliers.memoize方法組合,實現單例模式

3.可以考慮Supplier介面和Suppliers.memoizeWithExpiration方法組合,每隔一段時間更新快取的資料

深入的學習還是看原始碼,當做一個基礎工具的時候,可以考慮引入Guava,當寫一個新的方法時可以考慮看看Guava有沒有現成的^_^,如果沒有,仍然推薦使用Guava實現

一個Guava風格的方法。

參考資料:《Getting Started with Google Guava》