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数据库并从数据库中检索产品。之后可以将该产品添加到缓存中,以便后续调用不会到达数据库。
热门推荐
1 泰迪狗狗如何训练
3 狗狗训练图
5 狗狗训练方法
6 训练狗狗不咬人
8 敏捷训练狗狗
10 训练狗狗吃饭
11 泰迪狗狗训练
12 狗狗从多大开始训练
13 狗狗训练学校费用
14 怎么去训练狗狗
15 狗狗训练狗狗
16 狗狗训练教程
17 训练狗狗装死
18 泰迪狗狗的训练方法