views:

44

answers:

1

Hello. I have BeanTreeView, and some nodes in it. Every node has constructor

public class ProjectNode extends AbstractNode {

public ProjectNode(MainProject obj, DiagramsChildren childrens) {
    super (new ProjectsChildren(), Lookups.singleton(obj));
    setDisplayName ( obj.getName());

}

I set Rootnode as a root for tree in ExplorerTopComponent as this:

private final ExplorerManager mgr = new ExplorerManager();
    public ExplorerTopComponent(){
    associateLookup (ExplorerUtils.createLookup(mgr, getActionMap()));

    mgr.setRootContext(new RootNode());
}

And now, how I can get MainProject obj from some node? I need to get it in another class.

A: 

Hi badgirl/Joseph ;-)

To answer the title of your question (nothing about netbeans internals):

I think this question answers a little bit of your question what the lookup is: retrieving one or more implementation to the provided key which is normally an interface.

Then Joseph asked: 'which simple pattern can replace this anti pattern?'. You can't replace the lookup pattern in the NetBeans Platform but to answer his question: I would use dependency injection instead of lookup in my app via hand wiring, guice, pico container or even spring. The nice thing about such a library is that you configure just the dependencies and retrieve properly configured instances from the container. See this nice picture to get a feeling for this. (The most dependency injection tools allow also lifecycle management.)

To give an example for dependency injection via hand-wiring assume the following class:

class Path {
    List edges = new ArrayList();
    public void setEdges(List e) {
     edges = e;
    }
}

Now you can easily switch the ArrayList implementation with a LinkedList:

p = new Path();
p.setEdges(new LinkedList());

With the lookup concept this is not as easy (but I am not sure):

class Path {
  List edges = Lookup.create(List.class);
}

Now the usage with the linked list replacement is straight forward:

Lookup.set(List.class, LinkedList.class);
p = new Path();    

but the problem is: How would you use lookup if you have several different classes which needs a List implementation?

you implement your lookup depending on the class which uses it:

class Path {
  List edges = Lookup.get(Path.class).create(List.class);
}

But to be honest: I prefer the simple dependency injection way. Read this introduction where they also compared lookup and dependency injection (constructor + setter injection).

For more information read this interesting article from martin fowler which describes service locators (lookup) and inversion of control (dependency injection). Read here about the history of dependency injection.

Karussell