Singleton1.cs 773 B

1234567891011121314151617181920212223242526272829303132333435
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. namespace SingletonPattern
  7. {
  8. /// <summary>
  9. /// 单例模式实现方式一:
  10. /// 静态变量初始化
  11. /// </summary>
  12. public class Singleton1
  13. {
  14. /// <summary>
  15. /// 定义为static,可以保证变量为线程安全的,即每个线程一个实例
  16. /// </summary>
  17. private static Singleton1 instance = new Singleton1();
  18. private Singleton1()
  19. {
  20. }
  21. public static Singleton1 Instance()
  22. {
  23. return instance;
  24. }
  25. public void GetInfo()
  26. {
  27. Console.WriteLine($"I am {this.GetType().Name}.");
  28. }
  29. }
  30. }