单件模式笔记

单件模式:私有构造函数+静态变量+静态方法

 

    class Singleton

    {

        private static Singleton uniqueInstance; 静态实例

 

        private Singleton()

        { }     私有构造函数

 

        public static Singleton GetInstance()

        {

            if (uniqueInstance == null)

            {

                return new Singleton();

            }

            return uniqueInstance; 保证只有一个实例,且只有需要时才实例化(延迟实例化)。

        }

 

}

 

单件模式,一个类只有一个实例。并提供全局访问点。全局变量,多个实例共享一个变量。

单件模式问题:多线程问题。

多线程问题解决方案:急切实例化 private static Singleton uniqueInstance=new Singleton();

posted on 2010-04-19 18:33  mint5919  阅读(124)  评论(0)    收藏  举报