设计模式实践-代理模式
场景
在发送数据前和发送数据后调用方法
实现代码
发送接口
namespace DesignPatterns.Proxy
{
/// <summary>
/// 发射器接口
/// </summary>
public interface ISender
{
/// <summary>
/// 发送数据
/// </summary>
/// <param name="data">数据</param>
void Send(string data);
}
}
TCP发送类
namespace DesignPatterns.Proxy
{
/// <summary>
/// TCP发送器类型
/// </summary>
internal class TcpSender : ISender
{
/// <summary>
/// 发送数据
/// </summary>
/// <param name="data">数据</param>
public void Send(string data)
{
Console.WriteLine($"使用TCP发送数据: {data}");
}
}
}
代理发送类
namespace DesignPatterns.Proxy
{
/// <summary>
/// 发送器代理类
/// </summary>
public class SenderProxy : ISender
{
/// <summary>
/// 发送器对象
/// </summary>
private readonly ISender _sender = new TcpSender();
/// <summary>
/// 发送数据
/// </summary>
/// <param name="data">数据</param>
public void Send(string data)
{
this.BeforeSend();
Console.WriteLine("在代理中发送数据");
this._sender.Send(data);
this.AfterSend();
}
/// <summary>
/// 发送之前执行
/// </summary>
private void BeforeSend()
{
Console.WriteLine("发送数据之前");
}
/// <summary>
/// 发送之后执行
/// </summary>
private void AfterSend()
{
Console.WriteLine("发送数据之后");
}
}
}
相关调用
ISender sender = new SenderProxy();
sender.Send("test data");
Out
The id of meter is 1
发送数据之前
在代理中发送数据
使用TCP发送数据: test data
发送数据之后