- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading;
- namespace 单例模式演示
- {
- class Program
- {
- static void Main(string[] args)
- {
- //Singleton obj = new Singleton();
- //Singleton obj1 = new Singleton();
- //Singleton obj=new Singleton(
- //Singleton obj1 = Singleton.CreateInstance();
- //Singleton obj2 = Singleton.CreateInstance();
- //Singleton obj3 = Singleton.CreateInstance();
- //Singleton obj4 = Singleton.CreateInstance();
- //Console.Read();
- for (int i = 0; i < 1000; i++)
- {
- Thread t = new Thread(new ThreadStart(() =>
- {
- Singleton s = Singleton.CreateInstance();
- }));
- t.Start();
- }
- Console.WriteLine("ok");
- Console.ReadKey();
- }
- }
- //当把一个类的构造函数的访问修饰符该为private后,那么这个类在外部就不能被创建对象了(无法在外部调用构造函数,就无法在外部创建对象。)
- public class Singleton
- {
- private Singleton()
- {
- Console.WriteLine(".");
- }
- private static Singleton _instance;
- private static readonly object syn = new object();
- public static Singleton CreateInstance()
- {
- if (_instance == null)
- {
- lock (syn)
- {
- if (_instance == null)
- {
- //......
- _instance = new Singleton();
- }
- }
- }
- return _instance;
- }
- }
- public sealed class Singleton2
- {
- private Singleton2()
- {
- Console.WriteLine(".");
- }
- //静态成员初始化,只在第一次使用的时候初始化一次。
- private static readonly Singleton2 _instance = new Singleton2();
- public static Singleton2 GetInstance()
- {
- return _instance;
- }
- }
- }