六、单列模式-简单案例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 | 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" ; } } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | @{ Layout = null ; } <!DOCTYPE html> <html> <head> <meta name= "viewport" content= "width=device-width" /> <title>Index</title> </head> <body> <h3>@ViewBag.Message</h3> </body> </html> |
单列封装的类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 | 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就是类 } } } } |
点到为止
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步