单例模式是是常用经典十几种设计模式中最简单的。.NET中单例模式的实现也有很多种方式。下面我来介绍一下NopCommerce中单例模式实现。我之前的文章就分析了一下nop中EngineContext的实现。EngineContext是把一个Web请求用Nop的EngineCont ...
单例模式是是常用经典十几种设计模式中最简单的。.NET中单例模式的实现也有很多种方式。下面我来介绍一下NopCommerce中单例模式实现。
我之前的文章就分析了一下nop中EngineContext的实现。EngineContext是把一个Web请求用Nop的EngineContext引擎上下文封装。里面提供了一个IEngine的单例对象的访问方式。
下面就是EngineContext的源码:
一、EngineContext
1 using System.Configuration; 2 3 using System.Runtime.CompilerServices; 4 5 using Nop.Core.Configuration; 6 7 8 9 namespace Nop.Core.Infrastructure 10 11 { 12 13 /// <summary> 14 15 ///Provides access to the singleton instance of the Nop engine. 16 17 ///提供了访问单例实例Nop引擎 18 19 /// </summary> 20 21 public class EngineContext 22 23 { 24 25 #region Methods 26 27 28 29 /// <summary> 30 31 /// Initializes a static instance of the Nop factory. 32 33 /// 初始化静态Nop工厂的实例 34 35 /// </summary> 36 37 /// <param name="forceRecreate">创建一个新工厂实例,尽管工厂已经被初始化</param> 38 39 [MethodImpl(MethodImplOptions.Synchronized)] 40 41 public static IEngine Initialize(bool forceRecreate) 42 43 { 44 45 if (Singleton<IEngine>.Instance == null || forceRecreate) 46 47 { 48 49 Singleton<IEngine>.Instance = new NopEngine(); 50 51 52 53 var config = ConfigurationManager.GetSection("NopConfig") as NopConfig; 54 55 Singleton<IEngine>.Instance.Initialize(config); 56 57 } 58 59 return Singleton<IEngine>.Instance; 60 61 } 62 63 64 65 /// <summary> 66 67 /// Sets the static engine instance to the supplied engine. Use this method to supply your own engine implementation. 68 69 /// 设置静态引擎实例提供的引擎, 70 71 /// </summary> 72 73 /// <param name="engine">The engine to use.</param> 74 75 /// <remarks>Only use this method if you know what you're doing.</remarks> 76 77 public static void Replace(IEngine engine) 78 79 { 80 81 Singleton<IEngine>.Instance = engine; 82 83 } 84 85 86 87 #endregion 88 89 90 91 #region Properties 92 93 94 95 /// <summary> 96 97 /// Gets the singleton Nop engine used to access Nop services. 98 99 /// </summary>100 101 public static IEngine Current102 103 {104 105 get106 107 {108 109 if (Singleton<IEngine>.Instance == null)110 111 {112 113 Initialize(false);114 115 }116 117 return Singleton<IEngine>.Instance;118 119 }120 121 }122 123 124 125 #endregion126 127 }128 129 }
原标题:【NopCommerce源码架构学习
关键词:架构
*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们:
admin#shaoqun.com
(#换成@)。