匿名方法



正常我们在使用单例的时候,需要考虑线程安全,代码如下所示:

private object m_mutex = new object();
private bool m_initialized = false;
private BigInstance m_instance = null;

public BigInstance Instance
{
    get
    {
        if (!this.m_initialized)
        {
            lock (this.m_mutex)
            {
                if (!this.m_initialized)
                {
                    this.m_instance = new BigInstance();
                    this.m_initialized = true;
                }
            }
        }

        return this.m_instance;
    }
}

这样如果有多个单例,就违反了DRY原则
其实我们可以将它们封装到一处:

public class Lazy
{
    public Lazy(Func func)
    {
        this.m_initialized = false;
        this.m_func = func;
        this.m_mutex = new object();
    }

    private Func m_func;

    private bool m_initialized;
    private object m_mutex;
    private T m_value;

    public T Instance
    {
        get
        {
            if (!this.m_initialized)
            {
                lock (this.m_mutex)
                {
                    if (!this.m_initialized)
                    {
                        this.m_value = this.m_func();
                        this.m_func = null;
                        this.m_initialized = true;
                    }
                }
            }

            return this.m_value;
        }
    }
}

然后我们可以简化写成这样

private Lazy m_lazyInstance =
    new Lazy(delegate { return new BigInstance(); });

public BigInstance Instance { get { return this.m_lazyInstance.Instance; } }

使用Lamabda表达式如下:

private Lazy m_lazyInstance =
    new Lazy(() => new BigInstance());
public BigInstance Instance { get { return this.m_lazyInstance.Value; } }

匿名方法的缺点
匿名方法的优势在于自动形成闭包,而缺点也是让开发人员“不自觉”的创建了闭包,这样会使某些对象的生命周期加长。

欢迎留言

avatar
  Subscribe  
Notify of