1.为什么使用代理模式
在某些不能或者不方便直接调用对象时候,代理对象就是访问者和对象之间的中介。
2.代理模式的实现
实现要素:
- 抽象主题
- 具体主题
- 代理对象
代码实现
/// <summary>
/// 抽象主题
/// </summary>
public interface ISubject
{
void DoSomething();
List<string> GetSomething();
}
/// <summary>
/// 具体主题
/// </summary>
public class RealSubject : ISubject
{
public void DoSomething()
{
Console.WriteLine("执行DoSomething方法");
}
public List<string> GetSomething()
{
Thread.Sleep(3000);
List<string> result = new List<string>()
{
"111",
"222",
"333"
};
return result;
}
}
/// <summary>
/// 单例代理
/// </summary>
public class SingletonProxy : AbstractProxy
{
private static ISubject subject = new RealSubject();
public SingletonProxy()
{
}
public override void DoSomething()
{
subject.DoSomething();
}
public override List<string> GetSomething()
{
return subject.GetSomething();
}
}
/// <summary>
/// 异常代理
/// </summary>
public class ExceptionProxy : ISubject
{
private ISubject subject = new RealSubject();
public void DoSomething()
{
try
{
subject.DoSomething();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
public List<string> GetSomething()
{
try
{
return subject.GetSomething();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
return null;
}
}
/// <summary>
/// 缓存代理
/// </summary>
public class CacheProxy : ISubject
{
private ISubject subject = new RealSubject();
public void DoSomething()
{
subject.DoSomething();
}
public List<string> GetSomething()
{
string key = nameof(CacheProxy) + "_" + nameof(GetSomething);
if (CacheHelper.Exists(key))
{
return CacheHelper.Get<List<string>>(key);
}
else
{
List<string> result = subject.GetSomething();
CacheHelper.Add(key, result);
return result;
}
}
}
/// <summary>
/// 缓存帮助类
/// </summary>
public class CacheHelper
{
private static Dictionary<string, object> _DicCache = new Dictionary<string, object>();
public static void Add(string key, object value)
{
_DicCache.Add(key, value);
}
public static T Get<T>(string key)
{
return (T)_DicCache[key];
}
public static bool Exists(string key)
{
return _DicCache.ContainsKey(key);
}
}
以上便是代理模式的实现
3.总结一下
优点:上层与低层分离,一定程度上减少耦合、对目标对象的扩展、
缺点:增加了系统复杂度