c# 单例模式简单例子

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

/*单例模式确保一个类只有一个实例,并提供一个全局访问点*/

namespace 单例模式
{
    public class Singleton
    {
        //懒汉模式,只有在需要的时候才实例化
        /*饿汉模式,加载时即实例化
         * private static Singleton uniqueinstance = new Singleton();
         */
        //为了运行效率采用懒汉模式
        private static Singleton uniqueinstance;
        //为了实现多线程下的线程安全,使用互斥锁
        private static readonly object locker = new object();
        private Singleton()
        { }
        public static Singleton creatinstance()
        {
            //使用双重检测同步延迟加载去创建单例的做法是一个非常优秀的做法,
            //其不但保证了单例,而且切实提高了程序运行效率
            if (uniqueinstance == null)
            {
                lock (locker)
                {
                    if (uniqueinstance == null)
                    {
                        uniqueinstance = new Singleton();
                    }
                }
            }
            return uniqueinstance;
        }
        public void write()
        {
            Console.WriteLine("hello");
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            Singleton a = Singleton.creatinstance();
            a.write();
            //创建b的时候因为uniqueinstance不为空,所以跳过了实例creatinstance,返回了和a一样的creatinstance
            Singleton b = Singleton.creatinstance();
            b.write();
            Console.ReadKey();
        }
    }
}

    单例模式是最简单最常用的设计模式,主要用来读取保存系统的配置文件,在没有系统的学习设计模式前,我大都采用静态类来完成,学习比较,单例模式和静态类,总结各路大神们的观点,单例模式主要有一下几个优点:

    1,可以被延迟初始化,初始化比较灵活;2,单例模式可以有多态,而全静态的类不能支持多态;3,单例可以继承类,实现接口

    初学设计模式,只能照猫画虎,如果有大神能有更通俗易懂的解释还请不吝赐教,多谢!

参考:1,https://www.cnblogs.com/zhtao_tony/p/3956047.html

          2,https://blog.csdn.net/fuzhongmin05/article/details/71001857

          3,http://www.cnblogs.com/zhili/p/SingletonPatterm.html

    


  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值