之前在开发winform程序的时候,经常做这样的控制:每个form同时只能出现一个。方法有很多,通常我都采用这种方式:(通过一个public 的static 字段进行控制)
 主窗体menu:
我读设计模式--Singleton Patternprivate void subMenu1ToolStripMenuItem_Click(object sender, EventArgs e)
        }
frm窗体:
我读设计模式--Singleton Pattern public static bool sign = false;
我读设计模式--Singleton Pattern
我读设计模式--Singleton Pattern        
public frm()
        }
    这种方式可以很好的工作。
在Singleton Pattern,提到这种模式有几个特点:
  • 单例类只能有一个实例。
  • 单例类必须自己创建自己的唯一实例。 **
  • 单例类必须给所有其它对象提供这一实例。
    第二条中提到的,单例类只能自己控制,而不是由使用类的用户来控制单例(用户此时不知道是否单例),所以上述做法,虽然可以工作,但却不属于单件模式。
    我读设计模式--Singleton Patternnamespace SingletonDemo2
    }
    这是singleTon pattern的一般形式。
    应用单件模式也可以使上述实例很好的工作:
    frm:
    我读设计模式--Singleton Pattern public partial class frm : Form
        }
    主窗体menu中:
    我读设计模式--Singleton Patternprivate void menuToolStripMenuItem_Click(object sender, EventArgs e)
            }

  • 注意,多线程的程序中,上述简单写法让然可能造成多个实例,故而需要对线程安全性进行控制。
    1.双重锁定:

     frm;
            }
        }

    2.静态初始化:

     frm;
            }
        }

     

    单件模式的在多线程工作时更加有用。如果多个线程对一个类进行作业,如果各自产生自己的类实例,那结果必然是得不到我们的预期目的。这个时候,使用单件模式,使得不管有多少线程,工作的对象都只能是一个共同的实例,这才是我们想要的结果:(下面的例子引用自TerryLee的blog:多线程计数)

    我读设计模式--Singleton Patternusing System;
    我读设计模式--Singleton Pattern
    using System.Collections.Generic;
    我读设计模式--Singleton Pattern
    using System.Text;
    我读设计模式--Singleton Pattern
    using System.Threading;
    我读设计模式--Singleton Pattern
    我读设计模式--Singleton Pattern
    namespace SingletonDemo2
    }

    以上只是对单例模式的应用做了个简单的总结,有关理论还是要参照大牛们的blog:
    http://terrylee.cnblogs.com/archive/2005/12/09/293509.html

    相关文章:

    • 2022-01-17
    • 2022-03-02
    • 2022-01-31
    • 2022-01-15
    • 2021-07-18
    猜你喜欢
    • 2021-10-07
    • 2021-11-06
    • 2021-08-11
    • 2021-07-31
    • 2021-12-16
    相关资源
    相似解决方案