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

几种Aop实现

时间:2016-12-07 02:15:42      阅读:199      评论:0      收藏:0      [点我收藏+]

标签:private   []   访问者模式   模式   asp.net   run   null   nbsp   bsp   

1. 通过继承实现

public interface IA
{
    void DoSth();
}
public class A: IA
{
    public virtual void DoSth() { }
}
public class B : A,IA
{
    public override void DoSth()
    {
        before();
        base.DoSth();
        after();
    }

    public void before() { }
    public void after() { }
} 

2. 装饰者/代理模式(由继承改作组合)

public interface IA
{
    void DoSth();
}

public class A2: IA
{
    public void DoSth() { }
}
public class B2 : IA
{
    private IA a;
    public B2(IA a)
    {
        this.a = a;
    }
    public void DoSth()
    {
        before();
        this.a.DoSth();
        after();
    }
    public void before() { }
    public void after() { }
}

3. 访问者模式

public interface IA
{
    void DoSth();
}

public class A3 : IA
{
    public void DoSth() { }

    public void Proceed()
    {
        DoSth();
    }
}
public class MyInterceptor
{
    public void Intercept(IA invocation)
    {
        before();
        if(invocation != null)
            invocation.DoSth();
        after();
    }

    public void before() { }
    public void after() { }
}

  

4.ASP.NET MVC中的拦截器

public interface IAdditionalOp
{
    void before();
    void after();
}
public class AdditionalOp :Attribute, IAdditionalOp
{
    public void before() { }
    public void after() { }
}

public class A4
{
    [AdditionalOp]
    public void DoSth() { }
}

public class B4
{
    public void Run()
    {
        var classUnder = typeof(A4);
        var allMethods = classUnder.GetMethods();
        var methodUnder = allMethods.Where(m => m.Name == "DoSth");
        
        foreach (MethodInfo methodInfo in methodUnder)
        {
            Attribute[] attributes = Attribute.GetCustomAttributes(methodInfo, typeof(AdditionalOp));
            foreach (var item in attributes)
            {
                (item as AdditionalOp).before();
            }

            A4 a4 = new A4();
            a4.DoSth();

            foreach (var item in attributes)
            {
                (item as AdditionalOp).after();
            }
        }
    }
}

 5. 动态代理

.NET:动态代理的 “5 + 1” 模式

几种Aop实现

标签:private   []   访问者模式   模式   asp.net   run   null   nbsp   bsp   

原文地址:http://www.cnblogs.com/wj033/p/6139644.html

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