适配器模式绝对是软件开发当中最受关注的设计模式之一。
正如标题所说,我会直截了当的告诉你什么是适配器模式,不说太多的废话,因为设计模式这种东西需要慢慢的去体会。只有多思多闻,才能领会这些模式真的是设计的很巧妙。
public class Customer { } public interface ICustomerRepository { IList<Customer> GetCustomers(); }
public class CustomerService { private readonly ICustomerRepository _customerRepository; public CustomerService(ICustomerRepository customerRepository) { _customerRepository = customerRepository; } public IList<Customer> GetAllCustomers() { IList<Customer> customers; string storageKey = "GetAllCustomers"; customers = (List<Customer>)HttpContext.Current.Cache.Get(storageKey); if (customers == null) { customers = _customerRepository.GetCustomers(); HttpContext.Current.Cache.Insert(storageKey, customers); } return customers; } }
上面的代码有什么问题?
- 可测性 CustomerService这个类是在一个类库项目中,在一个类库项目中一旦出现HttpContext可测性将会变得非常差
- 灵活性 我们用HttpContext作为缓存方案,以后想换成别的,例如:Memcache或Redis,这个时候就得手动修改HttpContext方案替换为别的方案
解决办法:
public interface ICacheStorage { void Remove(string key); void Store(string key, object data); T Retrieve<T>(string key); }
public class CustomerService { private readonly ICustomerRepository _customerRepository; private readonly ICacheStorage _cacheStorage; public CustomerService(ICustomerRepository customerRepository, ICacheStorage cacheStorage) { _customerRepository = customerRepository; _cacheStorage = cacheStorage; } public IList<Customer> GetAllCustomers() { IList<Customer> customers; string storageKey = "GetAllCustomers"; customers = _cacheStorage.Retrieve<List<Customer>>(storageKey); if (customers == null) { customers = _customerRepository.GetCustomers(); _cacheStorage.Store(storageKey, customers); } return customers; } }
public class HttpContextCacheStorage : ICacheStorage { public void Remove(string key) { HttpContext.Current.Cache.Remove(key); } public void Store(string key, object data) { HttpContext.Current.Cache.Insert(key, data); } public T Retrieve<T>(string key) { T itemsStored = (T)HttpContext.Current.Cache.Get(key); if (itemsStored == null) { itemsStored = default(T); } return itemsStored; } }
我们已经封装了一个HttpContext缓存对象的适配器类,下一步是使用ICacheStorage接口注入它,不在本文讨论范围之内。将来如果使用不同的缓存方案,那么需要做的就是编写其他的适配器 如 Memcache,Redis。好了,就是这么直截了当。
时间: 2024-10-03 21:53:21