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(); } }
哲学管理(学)人生, 文学艺术生活, 自动(计算机学)物理(学)工作, 生物(学)化学逆境, 历史(学)测绘(学)时间, 经济(学)数学金钱(理财), 心理(学)医学情绪, 诗词美容情感, 美学建筑(学)家园, 解构建构(分析)整合学习, 智商情商(IQ、EQ)运筹(学)生存.---Geovin Du(涂聚文)