我有一些接口,以及一个实现此接口的类,说:
- interface IMyInterface
- {
- void Func1();
- void Func2();
- }
- class Concrete : IMyInterface
- {
- public virtual void Func1() { //do something }
- public virtual void Func2() { //do something }
- }
现在,我想创建一个类,用一些特定的逻辑来装饰每个具体的类方法,在非生产环境中,在调用之前和之后执行.
- class Decorator : Concrete
- {
- public override void Func1() { Pre(); base.Func1; Post(); }
- public override void Func2() { Pre(); base.Func2; Post(); }
- }
解决方法
就个人而言,我只需要明确记录需要的地方,但如果你设置使用装饰器这样做,你可以使用
RealProxy class.
它可能看起来像这样:
- public class DecoratorProxy<T> : RealProxy
- {
- private T m_instance;
- public static T CreateDecorator<T>(T instance)
- {
- var proxy = new DecoratorProxy<T>(instance);
- (T)proxy.GetTransparentProxy();
- }
- private DecoratorProxy(T instance) : base(typeof(T))
- {
- m_instance = instance;
- }
- public override IMessage Invoke(IMessage msg)
- {
- IMethodCallMessage methodMessage = msg as IMethodCallMessage;
- if (methodMessage != null)
- {
- // log method information
- //call method
- methodMessage.MethodBase.Invoke(m_instance,methodMessage.Args);
- return new ReturnMessage(retval,etc,etc);
- }
- }
- }