代码改变世界

BlogEngine中的BlogSettings

2010-11-26 20:44  MichaelYin  阅读(414)  评论(0编辑  收藏  举报

BlogEngine中的BlogSettings这个类是用来提供整个系统的设置参数的,参数的读取采用的是反射获取属性名称,然后遍历进行赋值,个人觉得这段代码值得学习

private void Load()
		{
			Type settingsType = this.GetType();

			//------------------------------------------------------------
			//	Enumerate through individual settings nodes
			//------------------------------------------------------------
			System.Collections.Specialized.StringDictionary dic = Providers.BlogService.LoadSettings();

			foreach (string key in dic.Keys)
			{
				//------------------------------------------------------------
				//	Extract the setting's name/value pair
				//------------------------------------------------------------
				string name = key;
				string value = dic[key];

				//------------------------------------------------------------
				//	Enumerate through public properties of this instance
				//------------------------------------------------------------
				foreach (PropertyInfo propertyInformation in settingsType.GetProperties())
				{
					//------------------------------------------------------------
					//	Determine if configured setting matches current setting based on name
					//------------------------------------------------------------
					if (propertyInformation.Name.Equals(name, StringComparison.OrdinalIgnoreCase))
					{
						//------------------------------------------------------------
						//	Attempt to apply configured setting
						//------------------------------------------------------------
						try
						{
							if (propertyInformation.CanWrite)
							{
								propertyInformation.SetValue(this, Convert.ChangeType(value, propertyInformation.PropertyType, CultureInfo.CurrentCulture), null);
							}
						}
						catch
						{
							// TODO: Log exception to a common logging framework?
						}
						break;
					}
				}
			}
			StorageLocation = Providers.BlogService.GetStorageLocation();
		}

在admin中对配置进行修改了以后,修改的是BlogEngine中的那个唯一的对象,然后调用Save方法通过反射重新生成一个StringDictionary然后将里面的数据存储数据库中完成对系统参数的修改。

另外一个就是它采用了单例模式这个设计模式,借着这个机会好好学习了下,这里推荐两篇个人觉得很不错的文章单件模式和这篇单例模式(Singleton),当然看完了以后可能也会和我一样产生一些疑问。比如说为什么BlogSettings没有考虑多线程的问题?它里面的代码直接就是

		public static BlogSettings Instance
		{
			get
			{
				if (blogSettingsSingleton == null)
				{
					blogSettingsSingleton = new BlogSettings();
				}
				return blogSettingsSingleton;
			}
		}

另外一个问题就是我在Bugnet系列的一篇文章中提到的是否必须一定要用单例模式的问题,Bugnet对于DAL层采用了单例模式的实现方式,当时我并不知道Bugnet 里的那个用法就是单例模式,当时就是觉得为什么不直接写成静态方法调用呢?那样也没什么问题,而且看的不是也很清楚么。到网上搜了一下,感觉大家也是各有说法,比如这个Javaeye讨论帖,再比如这个CSDN的讨论帖其中分歧在于大家对于需不需要完全OO的观点,有的人觉得静态方法对于OO来说实现方式太过于丑陋,而有的说做的事情本质其实差不多,一定要追求OO么?

虽然后来决定以后类似的情况用单例模式来做,但是如果你问我以前我问的那个问题,我自己说实话也不能说服我自己,希望有朝一日自己能基于自己的经验提出自己的看法。