我需要扩展实例的行为,但我无法访问该实例的原始源代码.例如:
/* I don't have the source code for this class, only the runtime instance */
Class AB
{
public void execute();
}
Run Code Online (Sandbox Code Playgroud)
在我的代码中,我会截取每个执行调用,计算一些sutff然后调用原始执行,类似于
/* This is how I would like to modify the method invokation */
SomeType m_OrgExecute;
{
AB a = new AB();
m_OrgExecute = GetByReflection( a.execute );
a.execute = MyExecute;
}
void MyExecute()
{
System.Console.Writeln( "In MyExecute" );
m_OrgExecute();
}
Run Code Online (Sandbox Code Playgroud)
那可能吗?
有没有人有这个问题的解决方案?
看起来你想要Decorator模式.
class AB
{
public void execute() {...}
}
class FlaviosABDecorator : AB
{
AB decoratoredAB;
public FlaviosABDecorator (AB decorated)
{
this.decoratedAB = decorated;
}
public void execute()
{
FlaviosExecute(); //execute your code first...
decoratedAB.execute();
}
void FlaviosExecute() {...}
}
Run Code Online (Sandbox Code Playgroud)
然后,您必须修改AB使用该对象的代码.
//original code
//AB someAB = new AB();
//new code
AB originalAB = new AB();
AB someAB = new FlaviosABDecorotor(originalAB);
/* now the following code "just works" but adds your method call */
Run Code Online (Sandbox Code Playgroud)