单例模式 – 默认属性
我一直在研究Singleton模式,因为它在Settings类中使用。 这是我的项目AccessTest的Settings.Designer.cs中的相关代码:
internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase { private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); public static Settings Default { get { return defaultInstance; } } public string applicationSetting1 { get { return ((string)(this["applicationSetting1"])); } } }
我不清楚的是为什么属性’applicationSetting1’是通过另一个属性’Default’访问的,为什么:
var value = AccessTest.Properties.Settings.Default.applicationSetting1;
我正在运行VS2013 C#和4.5。
因为defaultInstance
是静态的,而applicationSetting1
则不是。 这有效地使defaultInstance
成为类实例的管理者 。 当您在类上调用静态方法时,它不需要实例化,因此您知道您只能维护该类的单个实例。
回应您的意见:
Default
不是applicationSetting1的父级; Default
只是一个返回applicationSetting1实例的全局函数。 在单例模式的情况下,总是碰巧是同一个实例。
经理是我的名词。 为了更好地描述单例模式是什么,可以将其视为具有单个访问器的全局变量(我将其描述为管理器,仅仅因为它管理变量的生命周期)。
Normaly,您的Default属性称为Instance
所以你可以像这样打电话给你的单身:
Settings.Instance. X FUNCTION()
Erich Gamma的设计模式在设计模式上非常扎实。 您应该能够轻松地在网上找到PDF 🙂
顺便说一句,你还应该将它添加到你的默认/实例属性
If(defaultInstance == null) { defaultInstance = new Settings(); } return defaultInstance
这样你的单例永远不会为null并且实例化是懒惰的
单身人士模式上有很多post,但我找不到解决这个问题的任何post。 所以我想我会在我的秘密实验室借助你的post创建的这个例子中自己解释一下:
namespace MyProject.Properties { internal class Singleton { // Create an instance of the class itself. private static Singleton instance = new Singleton(); // Wrap the instance in a public property. public static Singleton Instance { get {return instance;} } // Prevent additional references from being created with a private constructor. private Singleton() { } // Create a non-static variable. public string nonStatic = "non static"; } }
我们对这个Singleton类了解如下:
- “实例”公共属性只能以静态方式访问。
- ‘nonStatic’无法静态访问,即只能通过引用访问。
- 私有构造函数阻止创建其他引用。
那么,如何从课外访问’nonStatic’呢?
该框架通过赋予静态“实例”以仅存在于单一情境中的魔力来解决困境:“实例”成为提供对任何非静态的访问的“桥梁”。 因此,此表格有效:
var value = MyProject.Properties.Singleton.Instance.nonStatic;
注意:在Settings.Designer.cs文件中使用我的Microsoft模式似乎不是真正的单例,因为默认构造函数允许创建其他引用。