田敏
返回博客列表
技术

代理模式的常见应用场景

田敏
2024-11-172 分钟阅读
Design PatternSoftware Engineering

代理模式(Proxy Pattern)是一种结构型设计模式,通过提供一个代理对象来控制对目标对象的访问。代理可以用来增强、控制或延迟实际对象的行为。这在需要控制访问权限、进行懒加载、执行缓存或添加日志的场景中非常有用。

代理模式的常见应用场景

  1. 远程代理(Remote Proxy):用于表示某个远程对象的本地代理,以便隐藏远程访问的细节。
  2. 虚拟代理(Virtual Proxy):在需要时才创建资源(如大对象、图像等),适合资源密集型对象的延迟加载。
  3. 保护代理(Protection Proxy):控制对资源的访问权限,常用于需要权限管理的场景。
  4. 缓存代理(Cache Proxy):用于在客户端和目标对象之间增加缓存机制,以提高性能。
  5. 智能代理(Smart Proxy):在调用目标对象之前或之后,执行其他操作,比如记录日志、监控性能等。

代理模式在 .NET 中的应用

.NET 中的代理模式被广泛应用于各种场景,尤其是依赖注入框架、AOP(面向切面编程)框架等。这些框架通过代理为服务对象添加行为,例如日志记录、事务控制和性能监控。

示例 1:基于接口的动态代理

在 .NET 中,Castle.DynamicProxy 是一个常用的库,用于创建动态代理。在以下代码示例中,通过代理对接口的实际实现进行拦截,并为目标对象添加了日志行为:

using Castle.DynamicProxy;
using System;

public interface IService
{
    void Execute();
}

public class RealService : IService
{
    public void Execute()
    {
        Console.WriteLine("Executing the main logic in RealService.");
    }
}

// 创建拦截器,添加日志
public class LoggingInterceptor : IInterceptor
{
    public void Intercept(IInvocation invocation)
    {
        Console.WriteLine($"Calling method {invocation.Method.Name}");
        invocation.Proceed();
        Console.WriteLine($"Method {invocation.Method.Name} executed.");
    }
}

// 代理创建示例
public class Program
{
    public static void Main()
    {
        var proxyGenerator = new ProxyGenerator();
        var proxy = proxyGenerator.CreateInterfaceProxyWithTarget<IService>(
            new RealService(),
            new LoggingInterceptor()
        );

        proxy.Execute();
    }
}

在这里,LoggingInterceptor 拦截了对 Execute 方法的调用,在方法执行前后加入了日志记录。

示例 2:保护代理应用(权限控制)

假设我们有一个敏感操作,只允许授权的用户执行。可以创建一个代理来检查用户权限,然后决定是否调用实际服务:

public interface IOperation
{
    void PerformSensitiveOperation();
}

public class SensitiveOperation : IOperation
{
    public void PerformSensitiveOperation()
    {
        Console.WriteLine("Performing a sensitive operation.");
    }
}

public class AuthorizationProxy : IOperation
{
    private readonly IOperation _operation;
    private readonly bool _hasPermission;

    public AuthorizationProxy(IOperation operation, bool hasPermission)
    {
        _operation = operation;
        _hasPermission = hasPermission;
    }

    public void PerformSensitiveOperation()
    {
        if (_hasPermission)
        {
            _operation.PerformSensitiveOperation();
        }
        else
        {
            Console.WriteLine("Access denied: You do not have permission to perform this operation.");
        }
    }
}

// 使用示例
public class Program
{
    public static void Main()
    {
        IOperation operation = new SensitiveOperation();
        IOperation proxy = new AuthorizationProxy(operation, hasPermission: false);

        proxy.PerformSensitiveOperation(); // 输出:Access denied: You do not have permission to perform this operation.
    }
}

在这个例子中,AuthorizationProxy 控制了对 SensitiveOperation 的访问,只有在 hasPermissiontrue 时才会执行实际操作。

示例 3:使用代理模式进行懒加载

在数据访问场景中,某些对象的数据量很大,不适合在初始化时加载全部数据。可以使用虚拟代理实现懒加载,当对象第一次访问时才加载数据:

public interface IDataLoader
{
    void LoadData();
}

public class RealDataLoader : IDataLoader
{
    public RealDataLoader()
    {
        Console.WriteLine("Initializing and loading all data...");
    }

    public void LoadData()
    {
        Console.WriteLine("Data loaded successfully.");
    }
}

public class LazyDataLoaderProxy : IDataLoader
{
    private RealDataLoader _realDataLoader;

    public void LoadData()
    {
        if (_realDataLoader == null)
        {
            _realDataLoader = new RealDataLoader();
        }
        _realDataLoader.LoadData();
    }
}

// 使用示例
public class Program
{
    public static void Main()
    {
        IDataLoader dataLoader = new LazyDataLoaderProxy();
        Console.WriteLine("Before accessing data loader.");
        dataLoader.LoadData();
        dataLoader.LoadData();
    }
}

在这个例子中,LazyDataLoaderProxy 代理类在第一次访问 LoadData() 时才创建 RealDataLoader 的实例,避免了不必要的资源浪费。

总结

代理模式在 .NET 中的主要应用体现在依赖注入、AOP、权限控制和懒加载等方面。通过代理模式,可以在不修改目标对象的前提下,添加或控制其行为。这种模式在系统架构的扩展和维护中有显著的优势。

版权协议:MIT返回列表