本示例演示如何DbProductRepository使用Decorator模式添加缓存功能。该方法遵循SOLID原则,因为它允许您添加缓存而不会违反单一职责原则或开放/封闭原则。
public interface IProductRepository
{
Product GetProduct(int id);
}
public class DbProductRepository : IProductRepository
{
public Product GetProduct(int id)
{
//返回从数据库检索的产品
}
}
public class ProductRepositoryCachingDecorator : IProductRepository
{
private readonly IProductRepository _decoratedRepository;
private readonly ICache _cache;
private const int ExpirationInHours = 1;
public ProductRepositoryCachingDecorator(IProductRepository decoratedRepository, ICache cache)
{
_decoratedRepository = decoratedRepository;
_cache = cache;
}
public Product GetProduct(int id)
{
var cacheKey = GetKey(id);
var product = _cache.Get<Product>(cacheKey);
if (product == null)
{
product = _decoratedRepository.GetProduct(id);
_cache.Set(cacheKey, product, DateTimeOffset.Now.AddHours(ExpirationInHours));
}
return product;
}
private string GetKey(int id) => "Product:" + id.ToString();
}
public interface ICache
{
T Get<T>(string key);
void Set(string key, object value, DateTimeOffset expirationTime)
}用法:
var productRepository = new ProductRepositoryCachingDecorator(new DbProductRepository(), new Cache()); var product = productRepository.GetProduct(1);
调用的结果GetProduct将是:从缓存中检索产品(装饰者职责),如果产品不在缓存中,则继续调用DbProductRepository数据库并从数据库中检索产品。之后可以将该产品添加到缓存中,以便后续调用不会到达数据库。