Design patterns 缓存装饰器
示例
本示例演示如何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数据库并从数据库中检索产品。之后可以将该产品添加到缓存中,以便后续调用不会到达数据库。
热门推荐
10 祝女儿简短祝福语大全
11 大学新年祝福语简短创意
12 元旦适合的祝福语简短
13 朋友出远门祝福语简短
14 初六简短的祝福语
15 祝男孩生日祝福语简短
16 同事调离的祝福语简短
17 拜年红包的祝福语简短
18 妈妈生日祝福语简短励志