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);
        }
}
This entry was posted on Friday, June 23rd, 2006 at 1:54 am and is filed under Uncategorized. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

1 Comment

  1. Anonymous says:

    Ey, obrigado!!!
    Com esta explicação consegui por o aspecto a funcionar no trabalho de ASSO :D

    ... on July July 2nd, 2007

Post a Comment