Guava的Supplier实现单例详解编程语言

1、函数式编程;

2、第一次get时才会初始化;

3、可以实现单例或缓存。

package suppliers; 
 
import com.google.common.base.Supplier; 
import com.google.common.base.Suppliers; 
import com.google.common.collect.Iterables; 
 
import java.util.ServiceLoader; 
 
/** 
 * @author xfyou 
 * @date 2018/7/30 
 */ 
public class Test { 
 
    public static void main(String[] args) { 
        try { 
            //shouldInitTheSupplierWrappedObjectWhenGetObject(); 
            shouldInitTheSupplierWrappedObjectForOnlyOneTime(); 
        } catch (Exception e) { 
            e.printStackTrace(); 
        } 
    } 
 
    private static void shouldInitTheSupplierWrappedObjectWhenGetObject() throws Exception { 
        Supplier<Integer> memoize = Suppliers.memoize(new Supplier<Integer>() { 
            @Override 
            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()); 
        System.out.println(memoize.get()); 
    } 
 
    private static void shouldInitTheSupplierWrappedObjectForOnlyOneTime() { 
        Supplier<Admin> memoize = Suppliers.memoize(new Supplier<Admin>() { 
            @Override 
            public Admin get() { 
                System.out.println("init supplier wrapped object"); 
                ServiceLoader<Admin> loader = ServiceLoader.load(Admin.class); 
                return Iterables.getFirst(loader, null); 
            } 
        }); 
        System.out.println(memoize.get()); 
        System.out.println(memoize.get()); 
        System.out.println(memoize.get()); 
    } 
}

 

package suppliers; 
 
/** 
 * @author xfyou 
 * @date 2018/7/31 
 */ 
public interface User { 
    /** 
     * @param firstName 
     * @param lastName 
     */ 
    void addUser(String firstName, String lastName); 
}

 

package suppliers; 
 
import lombok.ToString; 
 
import java.util.concurrent.atomic.AtomicReference; 
 
/** 
 * @author xfyou 
 * @date 2018/7/31 
 */ 
@ToString 
public class Admin implements User { 
    private static final AtomicReference<Admin> INSTANCE = new AtomicReference<>(); 
 
    public Admin() { 
        if (!INSTANCE.compareAndSet(null, this)) { 
            throw new IllegalStateException("This class only can be initialized once"); 
        } else { 
            System.out.println("Construct"); 
        } 
    } 
 
    @Override 
    public void addUser(String firstName, String lastName) { 
        System.out.println("Add new user"); 
    } 
}

 

原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/15922.html

(0)
上一篇 2021年7月19日
下一篇 2021年7月19日

相关推荐

发表回复

登录后才能评论