1.原有的代码
/// <summary>
/// 业务接口
/// </summary>
public interface ISubject
{
/// <summary>
/// get
/// </summary>
/// <returns></returns>
bool GetSomething();
/// <summary>
/// do
/// </summary>
void DoSomething();
}
/// <summary>
/// 一个耗时耗资源的对象方法
/// 一个第三方封装的类和方法
/// </summary>
public class RealSubject : ISubject
{
public RealSubject()
{
Thread.Sleep(2000);
long lResult = 0;
for (int i = 0; i < 100000000; i++)
{
lResult += i;
}
Console.WriteLine("RealSubject被构造。。。");
}
/// <summary>
/// 火车站查询火车票
/// </summary>
public bool GetSomething()
{
Console.WriteLine("坐车去火车站看看余票信息。。。");
Thread.Sleep(3000);
Console.WriteLine("到火车站,看到是有票的");
return true;
}
/// <summary>
/// 火车站买票
/// </summary>
public void DoSomething()
{
//Console.WriteLine("This is DoSomething Before");
//try
//{
Console.WriteLine("开始排队。。。");
Thread.Sleep(2000);
Console.WriteLine("终于买到票了。。。");
//}
//catch (Exception)
//{
// throw;
//}
}
}
2.矛盾的产生
业务需求的变更需要在原来基础上增加新的逻辑,但是原本的业务已经足够复杂不想破话原来的结构,比如缓存代理
3.解决
/// <summary>
/// 第三方缓存 能在内存中差常驻数据 且能获取
/// </summary>
public class CustomCache
{
private static Dictionary<string, object> CustomCacheDictionary = new Dictionary<string, object>
();
public static void Add(string key, object value)
{
CustomCacheDictionary.Add(key, value);
}
public static T Get<T>(string key)
{
return (T)CustomCacheDictionary[key];
}
public static bool Exist(string key)
{
return CustomCacheDictionary.ContainsKey(key);
}
}
public class ProxySubject : ISubject
{
private static ISubject _iSubject = new RealSubject();
public void DoSomething()
{
try
{
Console.WriteLine("This is DoSomething Before");
_iSubject.DoSomething();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
throw;
}
}
public bool GetSomething()
{
string key = $"{nameof(ProxySubject)}_{nameof(GetSomething)}";
bool bResult = false;
if (CustomCache.Exist(key))
{
bResult = CustomCache.Get<bool>(key);
}
else
{
bResult= _iSubject.GetSomething();
CustomCache.Add(key, bResult);
}
return bResult;
//return _iSubject.GetSomething();
}
}
4.总结
命名约束:XXXCacheProxy