我最近下载了一些示例以与 AppFabric 缓存一起使用。我注意到在示例中他们使用了带有静态方法的类而不是单例。
出于以下原因,我正在考虑将其更改为单例:
- 延迟加载
- 只有一个缓存实例...我想不出为什么需要多个实例的原因。
我是偏离目标还是正确赚钱?
下面是他们包含的一个类:
public class CacheUtil
{
private static DataCacheFactory _factory = null;
private static DataCache _cache = null;
public static DataCache GetCache()
{
if (_cache != null)
return _cache;
//-------------------------
// Configure Cache Client
//-------------------------
//Define Array for 1 Cache Host
List<DataCacheServerEndpoint> servers =
new List<DataCacheServerEndpoint>(1);
//Specify Cache Host Details
// Parameter 1 = host name
// Parameter 2 = cache port number
servers.Add(new DataCacheServerEndpoint("localhost", 22233));
//Create cache configuration
DataCacheFactoryConfiguration configuration =
new DataCacheFactoryConfiguration();
//Set the cache host(s)
configuration.Servers = servers;
//Set default properties for local cache (local cache disabled)
configuration.LocalCacheProperties =
new DataCacheLocalCacheProperties();
//Disable tracing to avoid informational/verbose messages on the web page
DataCacheClientLogManager.ChangeLogLevel(System.Diagnostics.TraceLevel.Off);
//Pass configuration settings to cacheFactory constructor
_factory = new DataCacheFactory(configuration);
//Get reference to named cache called "default"
_cache = _factory.GetCache("default");
return _cache;
}
最佳答案
是的。它很容易实现:
public class CacheUtil
{
private static DataCacheFactory _factory = null;
private static DataCache _cache = null;
// This is the single instance of this class
private static readonly CacheUtil instance = new CacheUtil();
private CacheUtil()
{
_cache = GetCache();
}
/// <summary>
/// Provides the single reference point to access this class
/// </summary>
public static CacheUtil Instance
{
get { return instance; }
}
private static DataCache GetCache()
{
if (_cache != null)
return _cache;
//-------------------------
// Configure Cache Client
//-------------------------
//Define Array for 1 Cache Host
List<DataCacheServerEndpoint> servers =
new List<DataCacheServerEndpoint>(1);
//Specify Cache Host Details
// Parameter 1 = host name
// Parameter 2 = cache port number
servers.Add(new DataCacheServerEndpoint("localhost", 22233));
//Create cache configuration
DataCacheFactoryConfiguration configuration = new DataCacheFactoryConfiguration {
Servers = servers,
LocalCacheProperties = new DataCacheLocalCacheProperties() };
//Disable tracing to avoid informational/verbose messages on the web page
DataCacheClientLogManager.ChangeLogLevel(System.Diagnostics.TraceLevel.Off);
//Pass configuration settings to cacheFactory constructor
_factory = new DataCacheFactory(configuration);
//Get reference to named cache called "default"
_cache = _factory.GetCache("default");
return _cache;
}
/// <summary>
/// Gets the cache
/// </summary>
public DataCache Cache { get; private set; }
}
关于c# - 缓存辅助类是单例模式的候选者吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5735818/