Singleton AspectIn this section we will transform our application to avoid multiple instances of the Fibonacci class to be created (I bet that you have been thinking we should had used the singleton pattern from the beginning…). This example is very useful as it shows how we can abstract of the application the fact we are using the singleton pattern. In this case, we want to intercept the calls to new Fibonacci and return a unique previously-created (if not exist, we will create one) instance. To do so, first we have to define a hookset that matches the constructor calls: Hookset theHookset = new PrimitiveHookset( Instantiation.class, new NameCS("reflex.examples.fibonacci.app.Fibonacci"), new InstantiationOfOS("reflex.examples.fibonacci.app.Fibonacci") );
Here we use a new kind of operation: instantiation. The instantiation operation matches all statements using the The declaration of the metaobject definition follows: MODefinition theMO = new MODefinition.SharedMO(new SingletonHandler());
Here we use the public static class SingletonHandler { private Fibonacci itsInstance = null; public Object ensureSingleton(IExecutionPointClosure aClosure){ if (itsInstance == null){ itsInstance = (Fibonacci) aClosure.proceed(); } return itsInstance; } }
As you can see, the (You can find more information about this closure object here). Finally, the code of the definition and configuration of the behavioral link is: BLink theLink = Links.get(theHookset, theMO); theLink.setControl(Control.AROUND); theLink.setCall(Control.AROUND, SingletonHandler.class.getName(), "ensureSingleton", Parameter.CLOSURE);
In the code above we set the control of the link as The complete code of the link provider that defines and configures this link is here. The command to run this example is: Windows
%java -classpath
"lib\javassist.jar;build\reflex-core.jar;build\reflex-examples.jar"
reflex.examples.tutorial.SingletonAspect
Linux
%java -classpath
"lib/javassist.jar:build/reflex-core.jar:build/reflex-examples.jar"
reflex.examples.tutorial.SingletonAspect
The output should be the same as executing the Fibonacci class without the aspect. You can verify the that the aspect is working adding a public Fibonacci(){ System.out.println("----- Fibonacci Constructor -----"); } This line should be printed once. |