Generic Observer Pattern with AspectJ
Been playing around with AspectJ and just made my first, not so simple, AspectJ code and it works like a charm. There are still some things that I don't fully understand but it's late so maybe tomorrow I'll get it.
Follow the read more link to see the source code for my Generic ObserverPattern implementation.
ObserverPattern.java
import java.util.Vector;PointObserverPattern.java
import java.util.Iterator;
public abstract aspect ObserverPattern perthis(subjectConstructed(Subject))
{
public interface Observer { }
public interface Subject { }
Vector observers = new Vector();
public void addObserver(Observer o)
{
observers.add(o);
}
protected pointcut subjectConstructed(Subject s) :
execution(Subject+.new(..)) && this(s);
abstract protected pointcut subjectChanged(Subject s);
after(Subject s) : subjectChanged(s)
{
Iterator itr = observers.iterator();
while (itr.hasNext())
updateObserver((Observer)itr.next(), s);
}
public abstract void updateObserver(Observer o, Subject s);
}
public aspect PointObserverPattern extends ObserverPatternPoint.java
{
declare parents: Screen implements Observer;
declare parents: Point implements Subject;
protected pointcut subjectChanged(Subject s) :
execution(void Point.set*(..)) && this(s);
public void updateObserver(Observer o, Subject s)
{
((Screen)o).updateDisplay();
}
}
public class PointScreen.java
{
private float x;
private float y;
Point (float x, float y)
{
this.x = x;
this.y = y;
}
public void setX(float x){
this.x = x;
}
public void setY(float y){
this.y = y;
}
}
public class ScreenApplication.java
{
public void updateDisplay(){
System.out.println("Display has been updated");
}
}
public class Application
{
public static void main(String[] args) {
Point p = new Point(0,0);
Screen s = new Screen();
PointObserverPattern.aspectOf(p).addObserver(s);
p.setX(2);
p.setY(2);
System.exit(0);
}
}
Com esta explicação consegui por o aspecto a funcionar no trabalho de ASSO :D (Comment this)