码迷,mamicode.com
首页 > 其他好文 > 详细

RealProxy实现AOP编程(2)

时间:2016-11-21 23:15:13      阅读:195      评论:0      收藏:0      [点我收藏+]

标签:turn   typeof   str   password   imessage   aop   sage   line   var   

稍微变化一下!注意区别。

Program.cs

class Program
{
  static void Main(string[] args)
  {
    User user = new User() { Name = "李四", Password = "12121" };
    var processor = TransparentProxy.Create(new 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 : 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();
    return new ReturnMessage(result, new object[0], 0, 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 IUserProcessor Create(IUserProcessor obj)
  {
    var processor = new UserProxyProcessor<IUserProcessor>(obj);
    IUserProcessor transparentProxy = (IUserProcessor)processor.GetTransparentProxy();
    return transparentProxy;
  }
}

 

RealProxy实现AOP编程(2)

标签:turn   typeof   str   password   imessage   aop   sage   line   var   

原文地址:http://www.cnblogs.com/Carroll4614/p/6087039.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!