我最近下载了一些用于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;
}
答案 0 :(得分:2)
我会说是的,我在我们的网络应用程序中使用单例模式进行缓存(针对我们自己的缓存接口)
答案 1 :(得分:2)
是。它很容易实现:
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; }
}
答案 2 :(得分:1)
我不明白你为什么要把类似乎是静态工厂的类改成Singleton。它也会进行延迟加载,并且也不会有多个实例。
编辑
工厂方法甚至更好,因为它返回一个接口(至少我猜是这样),所以它可以在不破坏客户端代码的情况下改变它在以后版本中的实现。