Skip to main content

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index] [List Home]
RE: [aspectj-users] Aspectj discussion

Title: Message
 
Yes, the idiom of using:
 
  - an interface to name a role within the pattern
  - having an aspect define advice and introductions on the interface
  - and using declare parents in other aspects to say what classes play the role in concrete patterns
 
is the way to go here.
 
One additional suggestion is to make the interface, i.e. Singleton, a protected inner interface of the
pattern, i.e. SingletonAspect.  That often makes code like this look better, because it makes it clear
that the interface really only has meaning withing the aspect (or extensions of the aspect).
 
 
 
Try this (again uncompiled untested code):
public interface Singleton
{
    // We use this interface with the sole purpose of marking which clases
    // are singleton. It is empty
}

public SingletonAspect
{
    private Map instances=new HashMap();

    pointcut instanceCreation(): initialization(Singleton+.new());

    Singleton around(): instanceCreation()
    {
       Singleton r=null;
       // Localize the class of the constructor being called
       Class instanceClass=thisJoinPointStaticPart.getSourceLocation().getWithinType();
       if(instances.containsKey(instanceClass))
          r=(Singleton)instances.get(instanceClass);
       else
       {
          r=(Singleton)proceed();
          instances.put(instanceClass, r);
       }
       return r;
    } 
}

So if you want the class sample.mypackage.MyClass to be a Singleton you write the following aspects:

public aspect MyClassIsASingleton
{
    // Make MyClass implements Singleton
    declare parents: sample.mypackage.MyClass implements Singleton;
}

As you can see this is truly reusable aspect. It's the same idea exposed in http://www.cs.ubc.ca/~jan/AODPs

As a guideline I prefer not to use introductions. Instead I use marker interfaces and Maps and Sets in the aspect.
This approach has a performance penalty if you have a huge number of classes (or objects, in the case of subject/observer pattern in http://www.cs.ubc.ca/~jan/AODPs ). The lookup (and insertion) time in the Map will degrade if we have a lot of entries (How many? I haven't measured it yet). But in the case of the SingletonAspect I expect you don't have more than 100 singletons in your system so performance it's not a problem. Other case could be the subject/observer pattern (potentially for hundred of thousand objects in really big systems).

Enrique J. Amodeo Rubio.

Back to the top