Friday, June 23, 2006

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;
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);
}
PointObserverPattern.java
public aspect PointObserverPattern extends ObserverPattern
{
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();
}
}

Point.java
public class Point
{
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;
}
}
Screen.java
public class Screen
{
public void updateDisplay(){
System.out.println("Display has been updated");
}
}
Application.java
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);
}
}
Posted by André Restivo at 01:54:02 | Permanent Link | Comments (1) |
Comments
1 - Ey, obrigado!!!
Com esta explicação consegui por o aspecto a funcionar no trabalho de ASSO :D (Comment this)

Written by: Anonymous at 2007/07/02 - 04:14:57
Write a comment