Search |
||
Refactor dynaop Factories using dynaopPosted by crazybob on June 22, 2004 at 12:25 PM PDT
dynaop uses class proxies to apply aspects to plain classes. Unlike dynamic proxies, class proxies do not require an interface. As a tradeoff, the framework must instantiate the object for you. The
Let's take an example class
public static class Foo {
String s;
int i;
public Foo(String s, int i) {
this.s = s;
this.i = i;
}
...
}
We can implement a factory that uses dynaop to create new instances of
public interface Factory {
Foo newFoo(String s, int i);
}
public class FactoryImpl implements Factory {
public Foo newFoo(String s, int i) {
// create a new instance of Foo using the default proxy factory
// and specified constructor arguments.
return (Foo) ProxyFactory.getInstance().extend(
Foo.class,
new Class[] { String.class, int.class },
new Object[] { s, new Integer(i) }
);
}
}
Note that every time we add a new type or constructor, we'll have to create another
We can use dynaop to refactor the
public class NewInterceptor implements Interceptor {
public Object intercept(Invocation i) throws Throwable {
Method m = i.getMethod();
return ProxyFactory.getInstance().extend(
m.getReturnType(),
m.getParameterTypes(),
i.getArguments() );
}
}
In the dynaop BeanShell configuration, apply interceptor(Factory.class, ALL_METHODS, new NewInterceptor());
Now we can instantiate
Factory factory = (Factory) ProxyFactory.getInstance().extend(Factory.class);
Foo foo = factory.newFoo("foo", 3);
As we add new types or modify their constructor arguments, we only need to tweak the »
Comments
Comments are listed in date ascending order (oldest first)
|
||
|
|