您的位置:首页 > 编程语言 > Java开发

struts2源码研究之设计模式准备

2017-07-09 21:13 423 查看
1、ThreadLocal 模式

通过阅读struts2的源码会发现很多地方都用到了ThreadLocal,为什么要用到这个呢?我们所知web service 是多线程场景下的服务,通过ThreadLocal 能很好的解决这个问题。sturts2在初始化的时候会产生很多在struts2整个生命周期中用到的变量。当在不同层次的调用中需要用到共享变量的情况下,为了避免发生多线程的问题,所以每一个线程都维护一个自己的变量。

上述所言,只是我个人的见解,可能有不正确的地方。

  言归正传,讲一讲什么是ThreadLocal。首先我们先看一下源码:

 /**

     * Sets the current thread's copy of this thread-local variable

     * to the specified value.  Most subclasses will have no need to

     * override this method, relying solely on the {@link #initialValue}

     * method to set the values of thread-locals.

     *

     * @param value the value to be stored in the current thread's copy of

     *        this thread-local.

     */

    public void set(T value) {

        Thread t = Thread.currentThread();

        ThreadLocalMap map = getMap(t);

        if (map != null)

            map.set(this, value);

        else

            createMap(t, value);

    }

/**

     * Returns the value in the current thread's copy of this

     * thread-local variable.  If the variable has no value for the

     * current thread, it is first initialized to the value returned

     * by an invocation of the {@link #initialValue} method.

     *

     * @return the current thread's value of this thread-local

     */

    public T get() {

        Thread t = Thread.currentThread();

        ThreadLocalMap map = getMap(t);

        if (map != null) {

            ThreadLocalMap.Entry e = map.getEntry(this);

            if (e != null)

                return (T)e.value;

        }

        return setInitialValue();

    }

通过阅读源码我们发现,在设置和取值的时候,ThreadLocal将当前线程作为key。由于当前线程只可能存在一个,这样就很好的维护了每一个线程都能够维护自己的值。通过将ThreadLocal设置为静态变量,这样就可以在不同层次的调用中这个共享变量了,因为是静态的且是线程安全的。

2、建造器模式。

对于建造器模式,我个人一开始不是很理解,为什么有new这个东西,我还需要建造器模式。带着这个疑问我学习了一下。

        首先先理解一下为什么要用构造器模式,构造器模式究竟有什么作用。

当我们创建一个对象的时候,如果是简单的创建一个对象,可以直接通过new来实列化,然而当我们构建一个对象,发现构建它的这个过程十分复杂的时候,我们就需要使用构造器模式来构建对象了,因为我们在写代码的时候需要做到单一职能的原则,new 只是做一件简单的事情,就是初始化对象,不需要去做一些复杂的逻辑处理。为了代码的可读性和易用性我们需要用一种代码技巧来处理这个问题,然而我们就需要用到建造器模式。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: