跨多个类存储通用设置的最佳模式 [英] Best Pattern for Storing Common Settings across Multiple Classes
问题描述
我正在创建两个单独的类来访问自定义文件.让我们将我的类称为MyReader
和MyWriter
.
I'm creating two separate classes for accessing a custom file. Let's call my classes MyReader
and MyWriter
.
我遵循的是.NET类(例如StreamReader
和StreamWriter
)所遵循的相同模式,其中有一个用于读写的单独类.除了遵循既定模式之外,这还为我解决了其他一些问题.
I'm following the same pattern that .NET classes such as StreamReader
and StreamWriter
follow, where there is a separate class for reading and writing. In addition to following an established pattern, this also solved some other problems for me.
但是,对于阅读器和编写器类,我确实需要一些通用设置.例如,我有一个分隔符,用户应该可以更改它.我也有一些固定数据,其中包含用于解析的常用信息.
However, I really need a few common settings for both the reader and writer classes. For example, I have a delimiter character that the user should be able to change. I also have some fixed data that contains common information used for parsing.
有人可以建议一种好的模式,尤其是遵循通用的.NET框架实践的模式,以便为多个此类创建通用设置吗?我的类已经从.NET类继承.似乎多重继承可能是一种方法,但C#似乎不支持这种方法.
Could someone suggest a good pattern, especially one that follows common .NET framework practices, for creating common settings for multiple classes like this? My classes already inherit from a .NET class. Seems like multiple inheritance might have been one way but doesn't seem supported in C#.
(我正在使用Visual Studio 2012.)
(I'm using Visual Studio 2012.)
推荐答案
This seems to be one of those rare instances where a Singleton might make good sense:
public abstract class MyBase
{
// This is the .NET class you're inheriting from, just putting it as a placeholder.
}
public class MyReader : MyBase
{
private static readonly IMySettings settings = MySettings.Instance;
}
public class MyWriter : MyBase
{
private static readonly IMySettings settings = MySettings.Instance;
}
internal interface IMySettings
{
// Define your setting's properties, such as delimiter character.
}
internal sealed class MySettings : IMySettings
{
private MySettings()
{
}
public static IMySettings Instance
{
get
{
return Nested.Instance;
}
}
// Implement your setting's properties, such as delimiter character.
private static class Nested
{
private static readonly IMySettings instance = new MySettings();
// Explicit static constructor to tell C# compiler not to mark type as beforefieldinit
static Nested()
{
}
public static IMySettings Instance
{
get
{
return instance;
}
}
}
}
希望这会有所帮助.
这篇关于跨多个类存储通用设置的最佳模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!