Saturday, September 20, 2008

Inner class

Could non-anonymous inner class or anonymous inner class be defined in
  • another class
  • interface
  • a method


=====================================================================

Here is one example from my project. We have an abstract class AbstractCatalogViewNeedChangeSetAction. It has a couple of sub classes, CreateCategoryAction, DeleteCategoryAction ... We want all the sub classes be registered to an publisher. The code to register to an publish is put in the abstract class using an inner class.
public abstract class AbstractCatalogViewNeedChangeSetAction {
public AbstractCatalogViewNeedChangeSetAction() {
super();
addObjectRegistryListener();
//each sub class construct should call super() so that it will be registered to the publisher.
}

private void addObjectRegistryListener() {
//ObjectRegistryListener is the interface of the listener.
ObjectRegistryListener objectRegistryListener = new ObjectRegistryListener() {
public void objectAdded(final String key, final Object object) {
setEnabled(canBeEnabled());
}

public void objectRemoved(final String key, final Object object) {
setEnabled(canBeEnabled());
}

public void objectUpdated(final String key, final Object oldValue, final Object newValue) {
setEnabled(canBeEnabled());
}
};

//ObjectRegistry is the publisher
ObjectRegistry.getInstance().addObjectListener(objectRegistryListener);
}

//this is the method should be implemented by different sub class.
protected abstract boolean canBeEnabled();

No comments:

Post a Comment