模式四(单子模式)

单例类只能有一个实例,单例类必须自己创建自己的唯一实例,单例类必须给所有其他对象提供这一事例。

 

using System;
using System.Collections.Generic;
using System.Text;
namespace Simple_Factory
{
    class Singleton
    {
        /// <summary>
        /// 私有的类对象
        /// </summary>
        private static Singleton instance;
        protected Singleton() { }
        public static Singleton Instance()
        {
            if (instance == null)
                instance = new Singleton();
            return instance;
        }
    }
    public class Client
    {
        public static void Main()
        {
            Singleton s1 = Singleton.Instance();
            Singleton s2 = Singleton.Instance();
            if (s1 == s2)
                Console.WriteLine("The same instance");
        }
    }
}
写法二:
sealed class Singleton
{
     private Singleton();
     public static readonly Singleton Instance=new Singleton();
}
Singleton类被声明为sealed,以此保证它自己不会被继承,将原来的Instance()方法变成public readonly,并在声明时被初始化,于是在初始化Instance属性的同时Singleton类实例得以创建和装载,而私有的构造函数和readonly()保证了Singleton不会被再次实例化。
但是该方式的缺点,无法实现延迟初始化。
写法三:
public sealed class Singleton
{
   Singleton(){}
  
   public static Singleton GetInstance()
  {
    return Nested.instance;
  }
   class Nested
  {
     static Nested()
     {}
    
      internal static readonly Singleton instance=new Singleton();     
  }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值