静态类与类的实例 [英] Static class vs. Instance of the class
问题描述
但是我可以使用单例模式创建非静态类,并使用它相同的方式。
问题:我的情况下哪种方法是正确的?
下面的示例显示您可以使用具有单例类的接口(这对静态类是不可能的)。
我喜欢这种模式,静态方法/属性或几个静态类。
这些接口可以提供主题特定的设置,甚至可以用作其他方法或类的参数,而没有那些类需要知道只要合同受到尊重,
公开密封类设置:IUserStettings,IOSettings
{
static readonly Settings instance = new Settings();
static设置(){}
设置(){}
public static设置实例
{
get {返回实例;
}
// - 接口实现
public string UserName
{
get {throw new NotImplementedException();
}
// --- etc ...
public string filename
{
get {throw new NotImplementedException() ; }
}
// - 接口实现
}
public interface IOSettings
{
string disk {get;}
string path {get; }
string filename {get;
}
public interface IUserStettings
{
string UserName {get; }
string Password {get; }
}
这可以以简单的方式使用:
IOSettings iosettings = Settings.Instance as IOSettings;
if(iosettings!= null){
Filereader.ReadData(IOSettings iosettings);
}
或
IUserSettings usersettings = Settings.Instance as IUserSettings;
if(usersettings!= null){
UserManager.Login(IUserSettings usersettings);
}
I have a static class which I use to get access to my public properties (global for whole app) and methods which I use during application run. For example I set some property in static class and during app run time I can get value from property.
But I can create non static class with singleton pattern and use it in the same way.
Question: Which approach is correct in my case?
The sample below shows that you can use interfaces with a singleton class (which is impossible with static class.)
I prefer this pattern above a large list of static methods/properties or several static classes.
Those interfaces can provide subject specific settings which can even be used as parameters to other methods or classes without that those classes need to know where the settings come from, as long as the contract is respected.
public sealed class Settings : IUserStettings, IOSettings
{
static readonly Settings instance = new Settings();
static Settings(){ }
Settings(){ }
public static Settings Instance
{
get { return instance; }
}
//-- interface implementation
public string UserName
{
get { throw new NotImplementedException(); }
}
// ---etc...
public string filename
{
get { throw new NotImplementedException(); }
}
//-- interface implementation
}
public interface IOSettings
{
string disk {get;}
string path { get; }
string filename { get; }
}
public interface IUserStettings
{
string UserName { get; }
string Password { get; }
}
And this can be used in a simple manner as as:
IOSettings iosettings = Settings.Instance as IOSettings;
if(iosettings!=null){
Filereader.ReadData(IOSettings iosettings);
}
or
IUserSettings usersettings = Settings.Instance as IUserSettings;
if(usersettings!=null){
UserManager.Login(IUserSettings usersettings);
}
这篇关于静态类与类的实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!