Decorator实现AOP编程。

时间:2023-01-01 21:00:53
Decorator实现AOP编程。

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 : IUserProcessor
{
  public void Shopping(User user)
  {
    Console.WriteLine("买呀,买呀,买苹果!");
  }
}

UserDecoratorProcess.cs

public class UserDecoratorProcess : IUserProcessor
{
  private IUserProcessor processor;

  public UserDecoratorProcess(IUserProcessor processor)
  {
    this.processor = processor;
  }

  public void Shopping(User user)
  {
    PreShopping();
    processor.Shopping(user);
    PostShopping();
  }

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

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

}