单件模式,就是确保一个类只有一个实例,并提供一个全局访问点。
代码
 1 namespace SingletonPatternSam
 2 {
 3     class Program
 4     {
 5         static void Main(string[] args)
 6         {
 7             SamSingleton.Instance.Display();
 8             Console.WriteLine(SamSingleton.Instance.ToString());
 9             Console.ReadLine();
10         }
11     }
12 
13     public sealed class SamSingleton
14     {
15         private static string str = "";
16         private static readonly SamSingleton instance = new SamSingleton();//构造实例对象
17         static SamSingleton()
18         {
19             str = "KKK";
20         }
21         public static SamSingleton Instance
22         {
23             get { return instance; }
24         }
25         
26         public void Display()
27         {
28             Console.WriteLine("XXXX");
29         }
30         public override string ToString()
31         {
32             return str;
33         }
34     }
35 }

 

相关文章:

  • 2021-05-31
  • 2021-10-08
  • 2021-05-19
  • 2021-06-06
  • 2021-06-09
  • 2022-01-15
  • 2021-07-06
  • 2021-09-21
猜你喜欢
  • 2021-08-19
  • 2021-10-06
  • 2022-01-09
  • 2022-01-08
  • 2022-02-01
  • 2021-12-30
  • 2021-07-13
相关资源
相似解决方案