什么叫”动态代理”,代理模式我们都知道,动态代理就是动态生成的代理(采用Emit)。5种代理模式:ClassProxy、ClassProxyWithTarget、InterfaceProxyWithoutTarget、InterfaceProxyWithTarget、InterfaceProxyWithTargetInterface、Mixin模式
重量级的ORM和IOC产品离不开动态代理,作为开发人员,多数情况不用关注动态代理的内部实现机制,但是了解其一般的规律和模式还是有必要的,比如:虽然你开发期间采用了POCO,因为开启了动态代理,运行期间则不是POCO。本文简单描述了5种代理生成模式和1种Mixin模式,最后给出一个示例。
{
void Play();
}
public class Animal : IPlayable
{
public virtual void Play()
{
Console.WriteLine(“Animal.Play”);
}
}
public class Dog : Animal
{
public override void Play()
{
Console.WriteLine(“Dog.Play”);
}
}
public interface IRunable
来源gaodaimacom搞#代%码网 {
void Run();
}
public class RunAbility : IRunable
{
public void Run()
{
Console.WriteLine(“RunAbility.Run”);
}
}
public class AnimalInterceptor : IInterceptor
{
public void Intercept(IInvocation invocation)
{
Console.WriteLine(“Before AnimalInterceptor.Intercept”);
if (invocation.InvocationTarget != null)
{
invocation.Proceed();
}
Console.WriteLine(“After AnimalInterceptor.Intercept”);
}
}
以上就是动态代理的5模式使用示例和Mixin模式的详细内容,更多请关注gaodaima搞代码网其它相关文章!