Guava的Supplier實現單例

FrankYou發表於2018-07-31

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");
    }
}

 

相關文章