使用Castle实现AOP
需要在vs上安装Castle.core
C#:
- using Castle.DynamicProxy;
-
- namespace MySport
- {
- //运动类接口
- internal interface Sports
- {
- public void Run();
-
- public void Dump();
- }
- //运动
- public class Sport : Sports
- {
- public virtual void Run()
- {
- Console.WriteLine("run...");
- }
-
- public virtual void Dump()
- {
- Console.WriteLine("dump...");
- }
- }
- }
-
- namespace AOPcore
- {
- //运动前、后需要做的事情
- public class AOPBase : IInterceptor
- {
- public void Intercept(IInvocation In)
- {
- WarmUp(In);
- In.Proceed();
- Stretch(In);
- }
- //运动前热身
- public void WarmUp(IInvocation In)
- {
- Console.WriteLine("before {0} warm up...", In.Method.Name);
- }
- //运动后拉伸
- public void Stretch(IInvocation In)
- {
- Console.WriteLine("after {0} stretch...", In.Method.Name);
- }
- }
- }
- using AOPcore;
- using MySport;
- using Castle.DynamicProxy;
-
- namespace program
- {
- public class Program
- {
- public static void Main()
- {
- ProxyGenerator proxyGenerator = new ProxyGenerator();
- AOPBase aopbase = new AOPBase();
- Sports sports = proxyGenerator.CreateClassProxyWithTarget(new Sport(),aopbase);
- //Sports sports = proxyGenerator.CreateClassProxy
(aopbase); - sports.Dump();
- sports.Run();
- }
- }
- }
不使用AOP的情况下需要修改sport类增加运动前后的扩展运动,使用了AOP之后我们不需要修改sport类,分离了扩展运动和核心运动的逻辑。让代码结构更加合理和优秀。