单例(C#版)

时间:2023-03-09 20:52:40
单例(C#版)

单例:

一个类只有一个实例。巧妙利用了编程语言的一些语法规则:构造函数private, 然后提供一个public的方法返回类的一个实例;又方法和返回的类的实例都是static类型,所以只能被类所拥有,而不能被实例化类的对象拥有。这样一个类就只能有一个实例了。

public class InstanceNote
    {
       private string Name;

private static InstanceNote _instance;
       public static  InstanceNote GetInstance()
       {
           if (_instance == null)
           {
               _instance = new InstanceNote();
           }
           return _instance;
       }

private InstanceNote()
       {
           Name = "Test";
       }
    }