RealProxy实现AOP编程(1)

时间:2022-10-20 06:51:15

Program.cs

class Program
{
  static void Main(string[] args)
  {
    User user = " };
    var processor = TransparentProxy.Create<UserProcessor>();
    processor.Shopping(user);
    Console.ReadLine();
  }
}

User.cs

public class User
{
  public string Name { get; set; }

  public string Password { get; set; }
}

IUserProcessor.cs

public interface IUserProcessor
{
  void Shopping(User user);
}

UserProcessor.cs

public class UserProcessor : MarshalByRefObject, IUserProcessor
{
  public void Shopping(User user)
  {
    Console.WriteLine("买呀,买呀,买桃子!");
  }
}

UserProxyProcessor.cs

class UserProxyProcessor<T> : RealProxy
{
  private T processor;

  public UserProxyProcessor(T processor) :
    base(typeof(T))//不能丢
  {
    this.processor = processor;
  }

  public override IMessage Invoke(IMessage msg)
  {
    PreShopping();
    IMethodCallMessage message = (IMethodCallMessage)msg;
    object result = message.MethodBase.Invoke(processor, message.Args);
    PostShopping();
    ], , null, message);
  }

  private void PreShopping()
  {
    Console.ForegroundColor = ConsoleColor.Red;
    Console.WriteLine("买东西前,判断是否注册了!");
    Console.ResetColor();
  }

  private void PostShopping()
  {
    Console.ForegroundColor = ConsoleColor.Red;
    Console.WriteLine("买完东西后,写个日志文件!");
    Console.ResetColor();
  }
}

TransparentProxy.cs

public static class TransparentProxy
{
  public static T Create<T>()
  {
    T instance = Activator.CreateInstance<T>();
    UserProxyProcessor<T> processor = new UserProxyProcessor<T>(instance);
    T transparentProxy = (T)processor.GetTransparentProxy();
    return transparentProxy;
  }
}

这里我们必须让 UserProcessor 类继承 MarshalByRefObject。很不好!