回头看singleton(单件)

来源:互联网 发布:保险网络大学考试报名 编辑:程序博客网 时间:2024/04/28 05:41

 

回头望,已过万重山

 

       出来工作有段时间拉,用设计模式也有一段时间了,这几天有空就整理一下。先说singleton(单件)吧。

 

刚学设计模式的时候(我开始是学c++和做j2me出身的)

 

public class Sample

{

    private static Sample _Instance;

 

    private Sample()

    {

    }

 

    public static Sample GetInstance()

    {

        if (null == _Instance)

        {

            _Instance = new Sample();

        }

        return _Instance;

    }

}

 

学会用get和set以后:

public class Sample

{

    private static Sample _Current;

 

    private Sample()

    {

    }

 

    public static Sample Current

    {

        get

        {

            if (null == _Current)

            {

                _Current = new Sample();

            }

            return _Current;

        }

    }

}

 

学会多线程操作以后:

public class Sample

{

    private static Sample _Current;

    private static object _threadlook = new object();

 

    private Sample()

    {

    }

 

    public static Sample Current

    {

        get

        {

            if (null == _Current)

            {

                lock (_threadlook)

                {

                    if (null == _Current)

                    {

 

                        _Current = new Sample();

                    }

                }

            }

            return _Current;

        }

    }

}

 

 

学会用MSIL以后:

public class Sample

{

    private static Sample _Current;

 

    private Sample()

    {

    }

 

    public static Sample Current

    {

        get

        {

            if (null == _Current)

            {

                lock (typeof(Sample))

                {

                    if (null == _Current)

                    {

 

                        _Current = new Sample();

                    }

                }

            }

            return _Current;

        }

    }

}

当然还有根据具体解决环境中添加了相应的关键字和相关的语句,大概数了一下,还有九种写法。由于环境描述的问题。在此略过。

现在回头看这些代码的写法,感触万分,当时每个阶段写出第一次这样的代码的时候,感觉开心极了,很成功的感觉,现在回头看,学海无涯,当初是多幼稚啊,想发笑。不过也体会到一句话:学过其他语言,只能很快的学会另一种语言,但是要弄懂、精通这种语言,还是要花很大功夫。

原创粉丝点击