CSharp: Singleton Pattern

 

    /// <summary>
    /// Summary description for Spooler.
    /// geovindu,Geovin Du,涂聚文
    /// 单例 模式(Singleton Patterns)
    /// </summary>
    public class Spooler
    {
        /// <summary>
        /// 
        /// </summary>
        private static bool instance_flag = false;
        /// <summary>
        /// 
        /// </summary>
        private Spooler()
        {
        }
        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public static Spooler getSpooler()
        {
            if (!instance_flag)
                return new Spooler();
            else
                return null;
        }

    }

  

    /// <summary>
    /// Summary description for SingletonException.
    /// geovindu,Geovin Du,涂聚文
    /// 单例 模式(Singleton Patterns)
    /// </summary>
    public class SingletonException : Exception
    {
        /// <summary>
        /// new exception type for singleton classes
        /// </summary>
        /// <param name="s"></param>
        public SingletonException(string s)
            : base(s)
        {
        }
    }

  

调用测试:

 /// <summary>
    /// geovindu,Geovin Du,涂聚文
    /// 单例 模式(Singleton Patterns)
    /// </summary>
    public partial class SingletonPatternsForm : Form
    {

        /// <summary>
        /// 
        /// </summary>
        public SingletonPatternsForm()
        {
            InitializeComponent();
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void SingletonPatternsForm_Load(object sender, EventArgs e)
        {

        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Click(object sender, EventArgs e)
        {
            Spooler sp1 = Spooler.getSpooler();
            if (sp1 != null)
            {
                this.textBox1.Text = "Got 1 spooler";
                Console.WriteLine("Got 1 spooler");
            }
            Spooler sp2 = Spooler.getSpooler();
            if (sp2 == null)
            {
                this.textBox2.Text = "Can\'t get spooler";
                Console.WriteLine("Can\'t get spooler");
            }
            else
            {
                
                this.textBox2.Text = "Got 2 spooler";
            }
            //fails at compile time 不可访问,受保护级别
           // Spooler sp3 = new Spooler();


        }
    }

  

posted @ 2022-09-18 16:41  ®Geovin Du Dream Park™  阅读(10)  评论(0编辑  收藏  举报