创建对象实例时使用内部类重写实例方法或属性

代码示例

public class SomeClass  {
	public String sayHi() {
		return "hi";
	}
}
public class SomeClassDoSomething {
	public static void main(String[] args) {
		S s = new S() {
			public String sayHi() {
				return "hello";
			}
		};
		System.out.println(s.sayHi());
		// print:hello
	}
}

结合泛型使用更加经典!

org.apache.commons.beanutils.ContextClassLoaderLocal<T>这个类的使用就用到了上述的技巧。

public class BeanUtilsBean {

    /**
     * Contains <code>BeanUtilsBean</code> instances indexed by context classloader.
     */
     //这里new了ContextClassLoaderLocal这个类,然后使用内部类的方式重写了`initialValue()`初始化方法
    private static final ContextClassLoaderLocal<BeanUtilsBean>
            BEANS_BY_CLASSLOADER = new ContextClassLoaderLocal<BeanUtilsBean>() {
                        // Creates the default instance used when the context classloader is unavailable
                        @Override
                        protected BeanUtilsBean initialValue() {
                            return new BeanUtilsBean();
                        }
                    };

    /**
     * Gets the instance which provides the functionality for {@link BeanUtils}.
     * This is a pseudo-singleton - an single instance is provided per (thread) context classloader.
     * This mechanism provides isolation for web apps deployed in the same container.
     *
     * @return The (pseudo-singleton) BeanUtils bean instance
     */
    public static BeanUtilsBean getInstance() {
        return BEANS_BY_CLASSLOADER.get();//调用`ContextClassLoaderLocal`的`get()`方法,往下看👇
    }
//...... 其余代码省略
}
public class ContextClassLoaderLocal<T> {
    private final Map<ClassLoader, T> valueByClassLoader = new WeakHashMap<ClassLoader, T>();
    private boolean globalValueInitialized = false;
    private T globalValue;

    /**
     * Construct a context classloader instance
     */
    public ContextClassLoaderLocal() {
        super();
    }
    //使用时若没有重写这个方法,返回的是null
    protected T initialValue() {
        return null;
    }

   
    public synchronized T get() {
     
        valueByClassLoader.isEmpty();
        try {

            final ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
            if (contextClassLoader != null) {

                T value = valueByClassLoader.get(contextClassLoader);
                if ((value == null)
                && !valueByClassLoader.containsKey(contextClassLoader)) {
                    value = initialValue();
                    valueByClassLoader.put(contextClassLoader, value);
                }
                return value;

            }

        } catch (final SecurityException e) { /* SWALLOW - should we log this? */ }

        // if none or exception, return the globalValue
        if (!globalValueInitialized) {
            globalValue = initialValue();
            globalValueInitialized = true;
        }//else already set
        return globalValue;
    }
    // ... ... 其余代码省略
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值