六、单列模式-简单案例

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Common;
using Microsoft.AspNetCore.Mvc;


namespace OTA.Controllers
{
    public class IndexController : Controller
    {
        public IActionResult Index()
        {

            Common.G<H>.Resolve.h();

            string s=Common.G<H>.Resolve.hh();

            ViewBag.Message = s;

            return View();

        }

    }

    // 调用的方法。
    public class H
    {
        public void h()
        {
            //return 2;
            Console.WriteLine("H2");
        }

        public string hh()
        {

            return "GG2";
        }

    }

}
@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>
    <h3>@ViewBag.Message</h3>
</body>
</html>

  

单列封装的类

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
//UnitOfWork
namespace Common
{

    //四、特例    这个实现不需要指定一个类
    public class UnitOfWork    //2、点列类加一个封装
    {
        private Dictionary<Type, Lazy<object>> Services { get; set; }

        private UnitOfWork()//构造函数 的时候new 一个Server 键值集合
        {
            Services = new Dictionary<Type, Lazy<object>>();
        }

        //单列模式-懒汉模式
        static UnitOfWork instance;  //或者  static F instance=null 写法
        static object locker = new object();  //返回对象实例用到的锁
        private static UnitOfWork Instance   //通过属性方式返回对象实例
        {
            get
            {
                lock (locker)
                {
                    if (instance == null)
                        instance = new UnitOfWork();
                    return instance;
                }
            }
        }
        public static T Resolve<T>() where T : new()//不过它调用的是这个  即定义公有方法提供一个全局访问点,同时你也可以定义公有属性来提供全局访问点
        {
            Lazy<object> service;
            if (Instance.Services.TryGetValue(typeof(T), out service))
            {
                return (T)service.Value;
            }
            else
            {
                Instance.Services[typeof(T)] = new Lazy<object>(() => new T());
                return Resolve<T>();
                //throw new KeyNotFoundException(string.Format("Service not found for type '{0}'", typeof(T)));
            }
        }

    }

    // 1、封装单列类的,这样单列类就不会对外公开使用了
    public static class G<T> where T : new() //使用的时候可以指定类型,这样就可以在类内使用    要求:  G类必须Status 且<T>泛型   好像加不加都行 为什么
    {
        public static void g()
        {
            Console.WriteLine("封装的外部类");
        }
        public static T Resolve  //单列不一定是返回自己,也可能返回其他的对象,这个“单”说的就是返回的对象永远的一个
        {
            get
            {
                return UnitOfWork.Resolve<T>();//这里的T就是类
            }
        }

    }


}

  

  

原文地址:https://www.cnblogs.com/fger/p/10573454.html