All Downloads are FREE. Search and download functionalities are using the official Maven repository.

commons.box.app.SObject Maven / Gradle / Ivy

The newest version!
package commons.box.app;

import commons.box.app.func.DataSupplier;

/**
 * 单例模式对象 使用时应该声明为 final 字段 然后通过 doGet 方法获取值
 */
public final class SObject implements DataSupplier {
    private final Object lock = new SafeObject<>();
    private final DataSupplier supplier;
    private transient volatile SafeObject object;

    /**
     * 构建无 supplier 的单例模式对象 此时仅可通过 doGet(Supplier supplier) 方法获取值
     */
    public SObject() {
        this.supplier = null;
    }

    /**
     * 构建 对象值通过 Supplier 获取
     * 

* supplier.doGet() 返回值必须不为空,否则每次调用时均会请求 supplier * * @param supplier */ public SObject(DataSupplier supplier) { this.supplier = supplier; } /** * 构建 直接生成实例 * * @param obj */ public SObject(T obj) { this.supplier = () -> obj; this.object = new SafeObject<>(obj); } /** * 通过定义的 supplier 获取数据 单例模式 * * @return */ public T get() { return this.get(this.supplier); } /** * 通过给定的 supplier 获取数据 单例模式 *

* 注意,此处定义的 supplier 仅变量不存在时才会调用 并非每次均调用 *

* supplier.doGet() 返回值必须不为空,否则每次调用时均会请求 supplier * * @param supplier * @return */ public T get(DataSupplier supplier) { if (this.object == null) { if (supplier == null) throw AppError.error("单例对象未定义 supplier"); synchronized (this.lock) { if (this.object == null) this.object = new SafeObject<>(supplier.get()); } } return (this.object != null) ? this.object.getObject() : null; } /** * 直接设置值 * * @param obj */ public void set(T obj) { synchronized (this.lock) { this.object = new SafeObject<>(obj); } } /** * */ public T raw() { return (this.object != null) ? this.object.getObject() : null; } /** * 清除当前值 */ public void clear() { synchronized (this.lock) { this.object = null; } } }





© 2015 - 2025 Weber Informatics LLC | Privacy Policy